Web Services 如何将PHP stdCLass对象转换为XML?

yacmzcpb  于 2022-11-15  发布在  PHP
关注(0)|答案(1)|浏览(144)

我使用这段代码连接到一个Web服务,它允许我检索电子商务产品的库存,但是,后者返回一个stdClass对象(如下图所示)。

$wsdl = "https://sinex-saas.com/blabla/Services/WebServiceStandard.asmx?WSDL";

$password = "????";
$username = "????";

$options = array(
    'user' => $username,
    'password' => $password,
);

$client = new SoapClient($wsdl);
$response = $client->RecupererEtatStock($options);
$presque = $response->RecupererEtatStockResult;

echo '<pre>';
print_r($presque);

我的目标是把这个stdClass对象转换成XML,这样我就可以把它用于WordPress插件了。你知道如何用PHP把stdClass转换成XML吗?

g2ieeal7

g2ieeal71#

不要试图构建一个通用的转换。读取一个特定的对象结构并从它创建一个DOM要容易得多。这允许你定义结构,验证和重新格式化值,忽略不需要的值,...

$data = getData();

$document = new DOMDocument();
// create and append a document element
$document->appendChild(
    $stock = $document->createElement('stock')
);

// iterate data array
foreach ($data->EtatStock as $stockData) {
    // create and append an element for each item
    $stock->appendChild(
        $item = $document->createElement('item')
    );
    // add a child element with text content
    $item
      ->appendChild($document->createElement('CodeMag'))
      ->textContent = $stockData->CodeMag;
    $item
      ->appendChild($document->createElement('LibMag'))
      ->textContent = $stockData->LibMag;
    // add value as an attribute 
    $item->setAttribute('quantity', $stockData->QteStock);
}

$document->formatOutput = true;
echo $document->saveXML();

function getData() {
    $json = <<<'JSON'
{
    "EtatStock": [
        {
            "CodeMag": "001",
            "LibMag": "SO SHOCKING",
            "QteStock": 2000
        }
    ]
}    
JSON;
    return json_decode($json);
}

输出量:

<?xml version="1.0"?>
<stock>
  <item quantity="2000">
    <CodeMag>001</CodeMag>
    <LibMag>SO SHOCKING</LibMag>
  </item>
</stock>

相关问题