I'm new to the world of XPath. I'm wanting to take an XML approach to powering my simple portfolio website instead of a database, which in this case would be superfluous as the only database element would be the projects themselves.
I've authored an XML file with the following structure:
<?xml version="1.0" encoding="UTF-8" ?>
<projects>
<project>
<title>A-Merchandise</title>
<slug>a-merchandise</slug>
<projectType>E-commerce</projectType>
<launchDate>2007-08-01</launchDate>
</project>
...
Now, I can parse this XML file fine with PHP for a listing overview, but how do I go about filtering projects with XPath? For example, how do I obtain all project
nodes that has a child projectType
node with the value e-commerce
?
Normally, I would run a SQL query like:
SELECT * FROM `projects` WHERE `category` = 'e-commerce';
What would the XPath equivalent be? Is my XML file in the right structure to accomodate this filtering?
Any pointers would be great. Thanks in advance.
I believe you want this:
/projects/project[projectType="e-commerce"]
The []
filter selects all project
elements under projects
who have a projectType
child with value "e-commerce"
I've also found this site to be very helpful for messing around with XPath and XSLT queries.
Further reading: http://www.w3schools.com/xpath/xpath_syntax.asp
considering your xml file name is foo.xml and is in same dir of bar.php which has content
$projects = simpleXMLElement('foo.xml',null,true);
$ecomProjects = $projects->xpath('project[projectType="E-commerce"]');
foreach($ecomProjects as $ecomProject)
{
echo $ecomProject; // or do whatever with it
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With