0

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?

12
  • Check your browser source page (CTRL+U in Chrome). You'll see the entire XML Commented Aug 15, 2017 at 11:02
  • 1
    echo $xml->asXml() is empty? Commented Aug 15, 2017 at 11:03
  • echo gettype($xml); returns object or string? Commented Aug 15, 2017 at 11:03
  • Ah, I see. Did you try $xml->ProductStock->Product->stock? Commented Aug 15, 2017 at 11:04
  • echo $xml->asXml() returns AA-HF461 23 Commented Aug 15, 2017 at 11:14

1 Answer 1

4

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());
Sign up to request clarification or add additional context in comments.

1 Comment

iainn - the second option works perfectly - echo (int) $xml->xpath('//stock')[0]; Many thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.