Google News
logo
PHP Get attribute values - loop
To get attribute values of XML elements in PHP using a loop, we can use the `attributes()` method of the SimpleXMLElement class along with a foreach loop. Here's an example :
Program :
$xmlString = '<root><person name="John" age="30"/><person name="Jane" age="25"/></root>';

$xml = simplexml_load_string($xmlString);

foreach ($xml->person as $person) {
    $name = $person['name'];
    $age = $person['age'];
    echo "Name: $name, Age: $age<br>";
}
Output :
Name: John, Age: 30
Name: Jane, Age: 25
In this example, we first load an XML string using the `simplexml_load_string()` function, which returns a SimpleXMLElement object. Then, we loop through each `person` element using a foreach loop.

Inside the loop, we use the `attributes()` method to get an array of attributes of the current element.

We then access the `name` and `age` attributes using array indexing, and print their values using the `echo` statement.