John Davidson

php - using xpath on non-hierarchical input

0 comments
Message:


I am using SimpleXML and xpath in PHP to read xml files. The problem is that the files (not of my own design) are not really hierarchical. For example:


<country>USA</country>
...
...
<city>Los Angeles</city>
<city>San Diego</city>
...
...
<country>Canada</country>
...
...
<city>Toronto</city>
<city>Banff</city>
...
...
<country>Scotland</country>
...
...
<city>Glasgow</city>
<city>Edinburgh</city>
<city>Banff</city>

The ... represent arbitrary amounts of other fields.
I can read the file with $xml = simplexml_load_file( 'filename' );
My problem is finding the <country> corresponding to each $xml->xpath("//city")


That is, I'd like to know how to address the country which last occurred in the xml data for each city



My Answer:
php
$xml = <<
Item 1
Item 2
Item 3

XML;

$simplexml = simplexml_load_string($xml);

// Use xpath to select all item elements
$items = $simplexml->xpath('//item');

foreach ($items as $item) {
echo $item . "\n";
}


In this example, the XML structure is not truly hierarchical as each `` element is a sibling of the others within the `` element. However, you can still use xpath to select all `` elements and iterate over them to access their values.

Rate this post

5 of 5 based on 4827 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us