Skip to content

How To Read XML file in PHP (SimpleXML)

How To Read XML file contnet in PHP using SimpleXML php extension. Reading XML file content in PHP script and convert them to object with SimpleXML.

Category
PHP
On this page

SimpleXML is a PHP extension introduced with PHP 5. It allows users to easily handle XML data in PHP. SimpleXML converts any XML data to an object which can be easily processed with normal property selectors and array iterators.

You must have installed php-simplexml extension on your system to use examples of this tutorial.

A Sample XML File

Here is a sample XML file used for this tutorial. The XML filename is employees.xml which you will see in further examples of this tutorial.

Read Specific XML Elements

Use simplexml_load_file function to load external XML file in your PHP program and create an object. After that, you can access any element from the XML by this object as follows.

Output:

Tom
Tyler

If the XML file is available on the remote server, you can use HTTP URL for the XML file as followings:

Read XML Elements In A Loop

In this example, we use the foreach method to iterate through the entire XML file and read elements from XML. Foreach loop access all children of an object.

Output:

Tom, Cruise, MD, 500000
Tyler, Horne, CEO, 250000

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

13 Comments

  1. hey,
    I store xml data in MySQL database. Now, I want to retrieve all the that data with PHP and show in a website.
    But it returns nothing

  2. if $xmldata containes a single quote how can that be handled ?
    I want to use something like str_replace(“‘”,” “,$xmldata) but that wont work

  3. Hi thank you for solution, for nested xml?
    Example:

    –
    63856
    –
    –
    NWBASO4ML-0008

    –
    NWBASO4ML-0005
    Base Solution N 4 ml in acqua

  4. There is an error on your sample code. You forget the s on implexml_load_file in your loop example. Please correct it.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top