Wednesday, 22 January 2020

How to Read XML using PHP

Let us start with a simple example, for that we need one simple XML file which might be returned in the response of any SOAP or REST.

1. create an XML file, let say we have this file with the name person.xml

<?xml version="1.0" encoding="utf-8"?>
<persons>
        <person id = "101">
            <name>Abdul Qadeer</name>
            <position>CEO</position>
        </person>
        <person id = "102">
            <name>Umar Adil</name>
            <position>CTO</position>
        </person>
</persons>

2. let's create another index.php file to read person.XML file

<?php
$xml = simplexml_load_file("person.xml");
//gets the contents of the person node.
$list = $xml->person;
for ($i = 0; $i< count($list); $i++) {
    //read the id attribute of person node
    echo "man no:" . $list[$i]->attributes()->id . "</br>";
    //read the child node name and postition of person node.
    echo "name: " . $list[$i]->name . "</br>";
    echo "position: " . $list[$i]-position . "</br>";
}

?>

No comments:

Post a Comment