Google News
logo
PHP Get node values - loop
To get the node values of all elements in an XML file, you can use a loop to iterate through each element and extract its value using SimpleXML in PHP. Here is an example code snippet :
Program :
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
<root>
  <item>
    <name>Item 1</name>
    <price>10.00</price>
  </item>
  <item>
    <name>Item 2</name>
    <price>20.00</price>
  </item>
</root>';

$xml = simplexml_load_string($xmlString);

foreach ($xml->item as $item) {
    $name = (string) $item->name;
    $price = (float) $item->price;
    echo "Name: $name, Price: $price\n";
}
This code loads an XML string using `simplexml_load_string()` and then iterates through each `<item>` element using a `foreach` loop.

The node values of the `<name>` and `<price>` elements are extracted using `(string)` and `(float)` type casting, respectively.

These values are then printed to the screen using `echo`.