Skip to Main Content
Upgrading to PHP 5
book

Upgrading to PHP 5

by Adam Trachtenberg
July 2004
Intermediate to advanced content levelIntermediate to advanced
350 pages
10h 9m
English
O'Reilly Media, Inc.
Content preview from Upgrading to PHP 5

SimpleXML

SimpleXML has been described as “the mostest bestest thing ever.” While it’s hard to live up to such grand praise, SimpleXML does do a remarkable job of making it—dare I say—simple to interact with XML. When you want to read a configuration file written in XML, parse an RSS feed, or process the result of a REST request, SimpleXML excels at these tasks. It doesn’t work well for more complex XML-related jobs, such as reading a document where you don’t know the format ahead of time or when you need to access processing instructions or comments.

Turning XML Documents into SimpleXML Objects

There are two ways to read XML under SimpleXML. If your XML document is stored as a string in a PHP variable, use simplexml_load_string( ). If it’s in a file, call simplexml_load_file( ) instead. For instance:

// Variable
$xml = simplexml_load_string('<xml>I am XML</xml>');

// Local file
$people = simplexml_load_file('address-book.xml');

SimpleXML Elements

SimpleXML turns elements into object properties. The text between the tags is assigned to the property. If more than one element with the same name lives in the same place (such as multiple <people>s), then they’re placed inside a list.

Element attributes become array elements, where the array key is the attribute name and the key’s value is the attribute’s value.

Figure 5-2 shows SimpleXML’s view of the start of the address book.

A SimpleXML representation of an XML address book

Figure 5-2. A ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert PHP and MySQL®

Expert PHP and MySQL®

Andrew Curioso, Ronald Bradford, Patrick Galbraith
Pro PHP Programming

Pro PHP Programming

Peter MacIntyre, Brian Danchilla, Mladen Gogala
Mastering PHP 7

Mastering PHP 7

Branko Ajzele

Publisher Resources

ISBN: 0596006365Supplemental ContentCatalog PageErrata