Showing posts with label introduction. Show all posts
Showing posts with label introduction. Show all posts

Wednesday, 20 August 2008

Introduction to SimpleXML with PHP

The SimpleXML php extension make it very easy to parse and create basic XML files.

Here is a basic xml file that describes a message from one person to another:
<?xml version='1.0'?>
<message>
<subject>Hello</subject>
<from>user@example.com</from>
<to>user2@example.com</to>
<body>Hello World</body>
</message>

If you create a file called test.xml with the content above then create a php file with the following, it will load in the xml file and output it as an SimpleXML object:

<?php
$xml = simplexml_load_file("test.xml");
print_r($xml);
?>
Will output:
SimpleXMLElement Object
(
[subject] => Hello
[from] => user@example.com
[to] => user2@example.com
[body] => Hello World
)
To reference a variable within the xml file you can use in the normal object way, e.g. $xml->subject

To change the value of a variable, you can simply do the following:
$xml->subject = "New Subject";

And to output the new XML file:
echo $xml->asXML();

which returns:
<?xml version="1.0"?>
<message>
<subject>New Subject</subject>
<from>user@example.com</from>
<to>user2@example.com</to>
<body>Hello World</body>
</message>
Any questions/feedback please leave a comment