Waloob73
Waloob73

Reputation: 77

PHP Parsing of XML Response from API

I have an XML response that I'm trying to extract a single item from, here is the response:

<GetProductStockResponse>
  <GetProductStockResult>
    <ProductStock>
      <Product>
        <sku>AA-HF461</sku>
        <stock>23</stock>
      </Product>
    </ProductStock>
  </GetProductStockResult>
</GetProductStockResponse>

If I echo this to the screen is is displayed as:

AA-HF461 23 

I tried using simplexml_load_string but it's not working, nothing comes out:

$res = $soapClient->GetProductStock($q_param);    
$clfResponse = $res->GetProductStockResult;
echo $clfResponse; // This works - see above

$xml = simplexml_load_string($clfResponse);
echo $xml; // This is empty         
echo $xml->stock; // This is empty

Am I making a schoolboy error?

Upvotes: 0

Views: 5201

Answers (1)

iainn
iainn

Reputation: 17434

echo $xml will print the string value of the outer tag of your XML. Since the GetProductStockResponse doesn't have any text content, there is no output. If you want to dump the full XML as a string, use

echo $xml->asXML();

echo $xml->stock; will also be empty, as the outer element does not contain a <stock> tag. If you want to drill down to it, you need to access it via each level of the document:

echo (int) $xml->GetProductStockResult->ProductStock->Product->stock; // 23

(The typecasts are important when dealing with SimpleXML elements, see this answer for more details)

If you want to be able to access elements from any level of the document, you can use SimpleXML's xpath method, like this:

echo (int) $xml->xpath('//stock')[0]; // 23

This will print the first <stock> element from any level of the document, but in general it's a better idea to navigate the document according to its structure.

Finally, if you are testing this via a browser, be aware that XML elements will not render correctly unless you escape the output:

echo htmlspecialchars($xml->asXML());

Upvotes: 4

Related Questions