What is this? From this page you can use the Social Web links to save Read XML files in PHP to a social bookmarking site, or the E-mail form to send a link via e-mail.

Social Web

E-mail

E-mail It
August 12, 2009

Read XML files in PHP

Posted in: Programming

PHP with XMLXML is very nice format for storing and especially transferring data between applications. Instead of old plain TXT files which you must parse from a strictly defined format, XML files gives your data 2nd dimension – a structure, so you basically “know” what data represents without need for parsing and cleaning it from rubbish.
Everybody is using it, so why shouldn’t you? :)

Also, one more advantage of using XML files is the fact that if someone add extra information into the file, your application will (probably) work without need for any changes, and that is great for systems that requires business continuity.

XML file is formated as a set of nodes and it’s sub-nodes, so when you’re trying to access some information you basically “asks” for a logical address and not a physical address in file.

Here’s an example.xml file:

  1.  
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <tasks>
  4. <note>
  5. <title>Buy bread</title>
  6. <detail>White bread, in a local supermarket.</detail>
  7. </note>
  8. <note>
  9. <title>Go to dentist</title>
  10. <detail>Bring SSN.</detail>
  11. </note>
  12. </tasks>
  13.  

A long time ago, PHP wasn’t supporting XML files, so you had to parse those XML files as they are plain TXT.

Nowadays, there is a set of built-in instructions in core PHP engine that allows you to easily read and write XML.

Following is a simple example that will print out the previous listed XML example in human readable format:

  1.  
  2. <?
  3.   $objDOM = new DOMDocument();
  4.   $objDOM->load("example.xml");
  5.  
  6.   $note = $objDOM->getElementsByTagName("note");
  7.  
  8.   foreach( $note as $value )
  9.   {
  10.     $title = $value->getElementsByTagName("title");
  11.     $strTitle  = $title->item(0)->nodeValue;
  12.  
  13.     $detail = $value->getElementsByTagName("detail");
  14.     $strDetail  = $detail->item(0)->nodeValue;
  15.     echo $strTitle." – ".$strDetail."
  16. ";
  17.   }
  18. ?>
  19.  

The output of running the code from above should be something like this:

Buy bread - White bread, in a local supermarket.
Go to dentist - Bring SSN.

For more information and how to write XML files look at SimpleXML for PHP.

 


Return to: Read XML files in PHP