Tuesday, 20 March 2007

Multiple nodes in PHP

Several of you have asked about looping round elements in XML. This is obviously desirable because, although only six places are asked for in the data, the code should not have to change when a new place is added.

Heres how to do it - [Caution - this code is unchecked]

//assume places.xml contains multiple places, each with a name and description

$placesxml = simplexml_load_file("places.xml");

$places = $placesxml->xpath("//Place");

// $places is now an array of XML elements, each a Place element

foreach ($places as $place) {

//$place now points to each Place in the XML document in turn
// so we can use object references to access the elements within a Place

print $place->name, $place->description;

// or even XPath expression as well

// and of course, if the are repeated elements in Place, such Link, with elements
//url and text, we can use a inner loop to work with these

foreach( $place->Link as $link) {
print "<a href='$link->url'/>$link->text</a>"

1 comment:

Anonymous said...

God artikel.

Sad og legede lidt med Node-lister og Binære-datastruktur i PHP. Og så manglede jeg nogle at medlem lagre node strukturen på.. og selvfølgelig: XML, OOPHP..

Hilsen Johs.