Xpath request with PHP (take two values)
Here is the XML code I'm working with:
<inventory> <drink> <lemonade supplier="mother" id="1"> <title>Super Lemonade</title> <price>$2.50</price> <amount>20</amount> </lemonade> <lemonade supplier="mike" id="4"> <title>Lemonade Plus</title> <price>$3.00</price> <amount>20</amount> </lemonade> <pop supplier="store" id="2"> <title>Poppys</title> <price>$1.50</price> <amount>10</amount> </pop> </drink> </inventory> Then I wrote simple code to work with XPath:
<?php $xmldoc = new DOMDocument(); $xmldoc->load('sample.xml'); $xpathvar = new Domxpath($xmldoc); $queryResult = $xpathvar->query('//lemonade/price'); foreach($queryResult as $result){ echo $result->textContent; } ?> This code works well, displaying all the lemonade price values โโas expected.
Now I need XPATH to get TITLE and SUPPLIER of all elements with quantity = 20.
How can i do this?
thanks
Using
/*/*/*[amount = 20]/@supplier | /*/*/*[amount = 20]/title This selects :
Any
supplierattribute of any element that is the grand-child of the top element of an XML document (same as/inventory/drink/lemonade, but I like to write short XPath expressions) whoseamountchild has a string value that can be assigned to number 20 .Any
titlechild of any element that is the grand-child of the top element of the XML document (same as/inventory/drink/lemonade, but I like to write short XPath expressions) whoseamountchild has a string value that can be numbered twenty.
XSLT Based Validation :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="node()|@*"> <xsl:for-each select= "/*/*/*[amount = 20]/@supplier | /*/*/*[amount = 20]/title"> <xsl:value-of select="."/> <xsl:text>
</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet> When this conversion is applied to the provided XML document :
<inventory> <drink> <lemonade supplier="mother" id="1"> <title>Super Lemonade</title> <price>$2.50</price> <amount>20</amount> </lemonade> <lemonade supplier="mike" id="4"> <title>Lemonade Plus</title> <price>$3.00</price> <amount>20</amount> </lemonade> <pop supplier="store" id="2"> <title>Poppys</title> <price>$1.50</price> <amount>10</amount> </pop> </drink> </inventory> it evaluates the XPath expression and copies the values โโof the selected modes on separate lines :
mother Super Lemonade mike Lemonade Plus Please note :
Your XPath training can be very useful with a tool like XPath Visualizer - used by many thousands of people learning XPath in a fun way.
In general, you want to use direct paths over the // search, because it is faster:
/inventory/drink/lemonade[amount=20]/title and
/inventory/drink/lemonade[amount=20]/@supplier You can combine both XPath queries with the | (UNION), which will then return four nodes.
Programmatic access to attributes with the DOM is explained in:
You can find a good XPath tutorial in