0

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 be Item 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 the xpath filter, getting the prices greater than 15.

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
}
sipher_z
  • 1,221
  • 7
  • 25
  • 48

1 Answers1

1

Your complete XPATH to get desired output Item 2 is:

//item[attributes[stock/amount='1'][price >= 15]]
Navin Rawat
  • 3,208
  • 1
  • 19
  • 31
  • Hi. I've updated my question, using your answer and i am getting a `array to string conversion error` when trying to output the elements – sipher_z May 22 '13 at 08:59
  • I am not very much aware about PHP. But, to resolve this problem you may follow http://stackoverflow.com/questions/12959196/array-to-string-conversion-error-in-php link – Navin Rawat May 22 '13 at 09:22
  • You're running another XPath on name tags, you will have to loop over its result. – Jens Erat May 22 '13 at 10:27
  • @sipher_z: You are likely just over-seeing a little detail, see: [Array to String conversion notice when getting $variable value with xpath](http://stackoverflow.com/a/16235134/367456) (Full-Length Description and Examples about that error) – hakre May 22 '13 at 14:23