Parse XML to an Object with PHP

By       
   

here.


Apache/2.4.18 (Ubuntu) Server at dcode.com.au Port 80
" data-via="andrewsirianni">Tweet

This script is a simple way of reading an XML file (or XML web address) and parsing it with PHP into an object. In this way you can then easily read the data within the XML and use it in a web application.

SimpleXML is the command to read the XML and put it into a PHP object. Here is an example:

Sample XML:


<people>
  <person>
    <fname>Andrew</fname>
    <sname>Sirianni</sname>
  </person>
  <person>
    <fname>John</fname>
    <sname>Smith</sname>
  </person>
  ...
</people>

Convert the XML to an object:


<?php
  $people = simplexml_load_file('people.xml');
?>

Then to access the data, you simply refer to the object in the following way:


<?php
  echo $people->person[0]->fname;
  # Would output "Andrew"
?>

And that's it! Now you can access elements of the XML file through the PHP object.

Enjoy! And please share your comments!



comments powered by Disqus

About Me

I design & develop software that runs on the Internet. As a qualified analyst, accountant and real estate agent, I can deploy systems that improve performance.

Categories


Warning: DOMDocument::load(https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5): failed to open stream: HTTP request failed! HTTP/1.0 410 Gone in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Warning: DOMDocument::load(): I/O warning : failed to load external entity "https://api.twitter.com/1/statuses/user_timeline.rss?screen_name=andrewsirianni&count=5" in /home/andrxvjf/public_etc/templates/rmargin/twitter.tpl.php on line 8

Recent Tweets

Follow me: @andrewsirianni




Copyright ©2012 Andrew Sirianni, All Rights Reserved   LinkedIn Profile