Jump to content

PHP get data from XML please help


Jamestown376

Recommended Posts

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 🙂

 

 

Link to comment
Share on other sites

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 by Barand
  • Great Answer 1
Link to comment
Share on other sites

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. 

  • Great Answer 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.