Home / Programming / How to loop through XML nodes with PHP

HowToPlaza Earn money writing

How to loop through XML nodes with PHP

by Sarah Watts

You can easily read XML data using PHP. All you have to do is loop through the individual nodes and either print the data on the web page or store it in an array. You just need an XML string and the PHP function simplexml_load_string().

Suppose you have the following XML string stored in a PHP variable:

<?php
$xmlString = ‘<?xml version=”1.0″ encoding=”UTF-8″?><items><item><name>Chair</name><price>$53</price></item><item><name>Table Lamp</name><price>$10</price></item><item><name>Table</name><price>$35</price></item><item><name>Pen Holder</name><price>$5</price></item></items>’;
?>

If you find it difficult to figure out this XML string in the PHP code, here’s how it looks in the browser:

Loop through XML nodes with PHP

We use the simplexml_load_string() in the following manner:

<?php
$xmldata = simplexml_load_string($xmlString);
?>

Once this is done, all we have to do is use the simple PHP foreach loop:

<?php
foreach($xmldata->item as $item)
{
        echo “<p>Item Name: ” . $item->name . “</p>”;
        echo “<p>Item Price: ” . $item->price . “</p>”;
}
?>

Sometimes certain XML nodes have attributes too. Let’s redefine the above mentioned XML string by adding an attribute “color” to the node name.

<?php
$xmlString = ‘<?xml version=”1.0″ encoding=”UTF-8″?><items><item><name color=”brown”>Chair</name><price>$53</price></item><item><name color=”red”>Table Lamp</name><price>$10</price></item><item><name color=”yello”>Table</name><price>$35</price></item><item><name color=”purple”>Pen Holder</name><price>$5</price></item></items>’;
?>

You can get the values of the attributes in the following manner:

<?php
$xmldata = simplexml_load_string($xmlString);
foreach($xmldata->item as $item)
{
        echo “<p>Item Name: ” . $item->name . “</p>”;
        echo “<p>Item Color: ” . $item->name["color"] . “</p>”;
        echo “<p>Item Price: ” . $item->price . “</p>”;
}
?>

This is a very simple example of looping through XML nodes using PHP, but you can gradually develop extremely complex functions using XML and PHP, and we shall explore them too here on HowToPlaza, so stay tuned.



Related posts

  • Hi Sarah,
    I stumbled across this tutorial, perhaps my ideas on using a dedicated XQuery processor might be useful to you or your readers.
    I posted it here: http://bit.ly/ah5Yu0
    It kind of resembles your post on the RSS reader too :-)
    Kind regards,
    Michael
blog comments powered by Disqus

Previous post:

Next post: