rockliner.blogg.se

Xpath get plain text
Xpath get plain text








xpath get plain text

$results = $xml->xpath('//employee/title|//employee/age') Going back to selecting various types of elements, you can use the | symbol (OR) to select more than one type of element, like this: You can even run queries on queries, with an XPath search like this: Once you get that, the other two are quite obvious:, xpath('//employee/age') The first query grabs all employees elements, then all employee elements inside it, but then filters them so that only those that have a name that matches Laura Pollard. The key part, is, of course, between the square brackets. Let's break that down to see how the querying actually works. $employees = $xml->xpath('/employees/employee[agename}" Įcho "Matching employees as old or older than 48" Matching employees with name 'Laura Pollard'" Įcho "Matching employees younger than 54"

xpath get plain text

You see, you can also use it to filter your results according to any values you want. So, what we have here is the ability to grab specific parts of a document very easily, but that's really only the start of XPath's coolness. The last one just looks for name elements, but note that it starts with "//" - this is the signal to do a global search for all name elements, regardless of where they are or how deeply nested they are in the document.

#Xpath get plain text full#

As a result, we get the full employee back, and need to print $employee->name to get the name. The second query matches all employee elements inside employees, but doesn't go specifically for the name of the employees. The first example says "Look in all the employees elements, find any employee elements in there, and retrieve all the names of them." It's very specific because only employees/employee/name is matched. The query itself has specialised syntax, but it's very easy. As you can see in the prototype, xpath() takes a query as its only parameter, and returns the result of that query. The key real work is done in the call to the xpath() function. What that does is pull out names of employees in three different ways. $employees = $xml->xpath('/employees/employee') $names = $xml->xpath('/employees/employee/name')

xpath get plain text

Using the same employees.xml file, give this script a try: That said, it might take a little while to get your head around all the possibilities it opens up to you! The standard way for searching through XML documents for particular nodes is called XPath, and Sterling Hughes (the creator of the SimpleXML extension) described it saying it's "as important to XML as regular expressions are to plain text".įortunately for us, XPath is a darn sight easier than regular expressions for basic usage.










Xpath get plain text