PHP Parsing of XML Response from API -


i have xml response i'm trying extract single item from, here response:

<getproductstockresponse>   <getproductstockresult>     <productstock>       <product>         <sku>aa-hf461</sku>         <stock>23</stock>       </product>     </productstock>   </getproductstockresult> </getproductstockresponse> 

if echo screen is displayed as:

aa-hf461 23  

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

$res = $soapclient->getproductstock($q_param);     $clfresponse = $res->getproductstockresult; echo $clfresponse; // works - see above  $xml = simplexml_load_string($clfresponse); echo $xml; // empty          echo $xml->stock; // empty 

am making schoolboy error?

echo $xml print string value of outer tag of xml. since getproductstockresponse doesn't have text content, there no output. if want dump full xml string, use

echo $xml->asxml(); 

echo $xml->stock; empty, outer element not contain <stock> tag. if want drill down it, need access via each level of document:

echo (int) $xml->getproductstockresult->productstock->product->stock; // 23 

(the typecasts important when dealing simplexml elements, see this answer more details)

if want able access elements level of document, can use simplexml's xpath method, this:

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

this print first <stock> element level of document, in general it's better idea navigate document according structure.

finally, if testing via browser, aware xml elements not render correctly unless escape output:

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

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -