Wikis & learning

Read records from a known XML format

An XML element may have attributes as well as child elements. Decide which represents the stable key and which contains text for display.

An XML element may have attributes as well as child elements. Decide which represents the stable key and which contains text for display.

Walkthrough

SimpleXML lets the example visit each book element, read its code attribute and cast its title to a string. This self-contained sample uses a known local XML string and does not fetch remote documents.

PHP example

<?php
$xml = simplexml_load_string('<library><book code="A1"><title>Maps</title></book><book code="B2"><title>Tools</title></book></library>', 'SimpleXMLElement', LIBXML_NONET);
if ($xml === false) { throw new RuntimeException('Invalid XML'); }
foreach ($xml->book as $book) {
    echo (string)$book['code'], ': ', (string)$book->title, PHP_EOL;
}

Expected output

A1: Maps
B2: Tools

Change and check

Add another book and a second attribute. Check that adding the attribute leaves the existing title extraction unchanged.