Parsing XML File with PHP

This code shows how to parse XML file in easy way using PHP.

[View All Snippets]
Show Plain Text »
  1. <?php
  2. // this is a sample xml string
  3. $xml_string="<?xml version='1.0'?>
  4. <text>
  5.    <article id='Article1'>
  6.        <title>Title 1</title>
  7.        <content>..text here..</content>
  8.    </article>
  9.    <article id='Article2'>
  10.        <title>Title 2</title>
  11.        <content>..text here..</content>
  12.    </article>
  13. </text>";
  15. // load this xml string using simplexml function
  16. $xml = simplexml_load_string($xml_string);
  18. // loop through the each node
  19. foreach($xml->article as $key){
  20.    // attribute are accessted by
  21.    echo $key['id'].' ';
  22.    // node are accessted by -> operator
  23.    echo $key->title.' ';
  24.    echo $key->content.'<br />';
  25. }
  26. ?>
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory

Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.

Quick Registration with: Facebook / Google