Example 1 — Add One Attribute
Add a lang attribute to the title element, then print the element as XML.
<?php
$book = simplexml_load_string('<book><title id="1">PHP</title></book>');
$book->title->addAttribute('lang', 'en');
echo $book->title->asXML(), PHP_EOL;
echo (string) $book->title['lang'], PHP_EOL; How It Works
- The title element starts with only an id attribute.
- addAttribute('lang', 'en') adds a second attribute to the same element.
- asXML() prints the updated element with both attributes.
- $book->title['lang'] reads the new value, cast to a string.

