Example 1 — Loop Over Attributes
Read every attribute of the book element with foreach.
<?php
$book = simplexml_load_string('<book id="7" lang="en"><title>PHP</title></book>');
foreach ($book->attributes() as $name => $value) {
echo $name, "=", (string) $value, PHP_EOL;
} How It Works
- The book element has two attributes, id and lang.
- attributes() returns an object that holds both of them.
- foreach gives the attribute name as the key and the value as an object.
- The value is cast to a string before it is printed.

