Compdigitec Labs

« | Home | »

SimpleXML – solution for XML manipulation in PHP

By admin | September 7, 2008

If you ever do get the need to manipulate (read/write) XML, you could try using the PHP DOM API, but it’s very difficult to use the DOM. An good extension-less way to access and manipulate XML instead is SimpleXML. It’s very easy to use compared to DOM and features a easy way to access attributes and tags in any XML document.

XML file (sample.xml)
<?xml version=”1.0″ ?>
<root><example>This is example number 1</example><example><tag>This is a tag.</tag></example></root>

Reading a XML file
$a = new SimpleXMLElement(file_get_contents(“sample.xml”));
echo $a->example[0];

The example above will read the sample XML file above and will output the contents of the first <example> element.

Writing a XML file

$a = new SimpleXMLElement(‘<?xml version=”1.0″ ?><root></root>’);
for($i = 1; $i <= 9; $i++) {
echo $a->asXML();

The above example will create the following XML file:

<?xml version=”1.0″?>

So as you can see, you can very easily manipulate XML with SimpleXML. Don’t forget to subscribe to Compdigitec Labs for more interesting articles!

If you found this article helpful or interesting, please help Compdigitec spread the word. Don’t forget to subscribe to Compdigitec Labs for more useful and interesting articles!

Topics: (X)HTML, PHP | 1 Comment »

One Response to “SimpleXML – solution for XML manipulation in PHP”

  1. url Says:
    April 7th, 2024 at 07:26

    … [Trackback]

    […] Info on that Topic: […]