Jamestown376 Posted August 6, 2020 Share Posted August 6, 2020 Hi I need to use PHP to get data from an XML document of items. The XML doc looks like this <STOREITEMS> <PRODUCT ITEM="dj91ja" NAME="Mushroom Soup"> <STOCK>In Stock</STOCK> </PRODUCT> <PRODUCT ITEM="09shjk1" NAME="Chicken Soup"> <STOCK>In Stock</STOCK> </PRODUCT> <PRODUCT ITEM="mgm826ga" NAME="Vegetable Soup"> <STOCK>No Stock.</STOCK> </PRODUCT> </STOREITEMS> I need to find out if a product is in stock based on the ITEM attribute, for example 09shjk1 This is my code: $product_queried = '09shjk1'; $xml=simplexml_load_string($xmlstr) or die("Error: Cannot make object"); foreach($xml->children() as $items) { if($items->PRODUCT['ITEM'] == $product_queried){ echo 'Product stock : ' . $items->STOCK . ''; } } Unfortunately it's not working. I need to be able to change the $product_queried to get the stock of the item from the XML document. Can anyone advise? Sorry if it's completely wrong I am new to XML. Many thanks in advance 🙂   Quote Link to comment https://forums.phpfreaks.com/topic/311283-php-get-data-from-xml-please-help/ Share on other sites More sharing options...
requinix Posted August 6, 2020 Share Posted August 6, 2020 Is STOREITEMS the root node? Then each $items will be a single PRODUCT... Quote Link to comment https://forums.phpfreaks.com/topic/311283-php-get-data-from-xml-please-help/#findComment-1580394 Share on other sites More sharing options...
Barand Posted August 6, 2020 Share Posted August 6, 2020 (edited) try $product_queried = '09shjk1'; $xml=simplexml_load_string($xmlstr) or die("Error: Cannot make object"); $items = $xml->xpath("//PRODUCT[@ITEM='$product_queried']"); if ($items) echo $items[0]['ITEM'] . ' - ' . $items[0]->STOCK . '<br>'; else echo "Not found"; Â Edited August 6, 2020 by Barand 1 Quote Link to comment https://forums.phpfreaks.com/topic/311283-php-get-data-from-xml-please-help/#findComment-1580396 Share on other sites More sharing options...
Phi11W Posted August 6, 2020 Share Posted August 6, 2020 6 hours ago, Jamestown376 said: I need to find out if a product is in stock based on the ITEM attribute This XPath expression will find a product if it is is stock and return no items if it's not. $items = $xml->xpath( "/ STOREITEMS / PRODUCT [ @ITEM = '$product_queried' and STOCK / text() = 'In Stock' ] " ); Regards,   Phill W. 1 Quote Link to comment https://forums.phpfreaks.com/topic/311283-php-get-data-from-xml-please-help/#findComment-1580402 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.