'How can I convert a PHP stdCLass object to XML?

I use this code to connect to a web service that allows me to retrieve a stock of products for e-commerce. However, the latter returns a stdClass Object (photo below).

$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);

My goal is to convert this stdClass object to XML so that I can use it for a WordPress plugin. Do you know how to convert a stdClass to XML with PHP?

stdClassObject photo



Solution 1:[1]

Don't try to build a generic convert. It is a lot easier just to read a specific object structure and create a DOM from it. This allows you to define the structure, validate and reformat the values, ignore unneeded values, ...

$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);
}

Output:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ThW