Getting started with Xpath
Its been a long time since my last post and now I came up with a new subject interesting to me because I could find around me people that know and understand Xpath, so here I'm going to show what I've found about Xpath and the little particularities on it in PHP.
A little bit of history
Xpath was created to be able to easily navigate between nodes in a XML document and be able to find specific node as well by criteria using a query language.
The Xpath became famous for its light sintax and facilities of manipulating nodes on XML documents. Xpath sintax queries are alike URL's, for example you can use a common XPath such as "/rootNode/child/lastchild" to refer to lastchild directly, let's see the example bellow and make the things cleaner.
Following our thoughts to reach the tag
*tip: Google for xpath tester and try out the examples in this post
|/||Selects from the root node|
|//||Selects nodes in the document from the current node that
match the selection no matter where they are
|.||Selects the current node|
|..||Selects the parent of the current node|
Example from w3schools : http://www.w3schools.com/xpath/xpath_syntax.asp
Xpath and PHP
Now we have the basics of Xpath we can play around with PHP and see how it interacts with Xpath. The first thing we must have in mind is that PHP have two alternatives to accomplish this task and one is using simplexml family functions or we have also the DOMXpath family.
Using simplexml the function will return to us all matched elements inside an array with SimpleXMLElement on it.
Otherwise we can use the DOMXpath to complete or task but we will need a few more lines but we have a OOP approach.
Therefore the return change as well
Try it yourself
We have many possibilities when we are using Xpath and also we can do a lot of things with it, the only way to get know is getting your hands dirty and try different queries in different files!