php - Multiple filters using xPath

75

I have some XML in the following format

<root>
 <item>
   <created>2013-05-21</created>
   <name>Item 1</name>
     <attributes>
       <stock>
         <amount>1</amount>
       </stock>
       <price>10</price>
     </attributes>
  </item>
  <item>
   <created>2013-05-21</created>
   <name>Item 2</name>
     <attributes>
       <stock>
         <amount>1</amount>
       </stock>
       <price>20</price>
     </attributes>
  </item>
  <item>
   <created>2013-05-21</created>
   <name>Item 3</name>
     <attributes>
       <stock>
         <amount>2</amount>
       </stock>
       <price>10</price>
     </attributes>
  </item>
</root>

I'm trying to get the following:

1 - Get all items that have a stock amount that is 1

2 - Get all of the filtered items that have a price greater than or equal to 15

This means in the above, the result would beItem 2

I have following so far:

$xml = new SimpleXMLElement($xmlString);
$xmlReturn = $xml->xpath("item[attributes/stock[contains(amount,'1')]]");

I can then loop through and get the XML as follows:

foreach($xmlReturn as $node){
  echo $node->asXml();
}

The problem is the second part of thexpath filter, getting the prices greater than15.

I've tried:

$test = $xml->xpath("item[attributes/[price>15]]");

But that gives me an error:

Warning: SimpleXMLElement::xpath(): Invalid expression

Can I combine the two searches into a single filter?

Thanks

UPDATED

$data = 'XML DATA HERE';
$xml = new SimpleXMLElement($data);
$xpath = $xml->xpath("//item[attributes[stock/amount='1'][price >= 15]]");

foreach($xpath as $node)
{
   echo $node->xpath('name');
   // this throws a Notice: Array to string conversion error
}
640

Answer

Solution:

Your complete XPATH to get desired outputItem 2 is:

//item[attributes[stock/amount='1'][price >= 15]]

People are also looking for solutions to the problem: php - posting serialized data with jquery ajax in IE6 not working

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.