Manipulate a XML File Using PHP

“Hi, in this post I’m going to explain how we can manipulate a XML file from PHP and give you an example for the same. When we start working with XML for the first time, it is difficult to understand how we can manipulate a XML file. I use the DOMDocument to manipulate the XML file which I show in the following example. You can use PHPcodepad to test the example which I’m discussing here. I hope this post will be useful for you!”

Let’s assume we have the following XML file.

$xml = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
    <Shop>
        <ItemList>
             <Item>
                 <Id>1</Id>
                 <Name>Pencil - 9H</Name>
                 <Description>9H - Hardest pencil available in the world</Description>
                 <Price>$1</Price>
             </Item>
             <Item>
                 <Id>2</Id>
                 <Name>Pencil - F</Name>
                 <Description>F - Medium pencil available in the world</Description>
                 <Price>$0.8</Price>
             </Item>
             <Item>
                 <Id>3</Id>
                 <Name>Pencil - 9B</Name>
                 <Description>9B - Softest pencil available in the world</Description>
                 <Price>$0.6</Price>
             </Item>
             <Item/>
         </ItemList>
     </Shop>
XML;

Now think that we need to do the following modifications to the above XML file.

1. Change the first pencil’s detail as follows.

<Price>$1.2</Price>

2. Add the following pencil right after the first pencil.

<Item>
     <Id>4</Id>
     <Name>Pencil - 8H</Name>
     <Description>8H - Second hardest pencil available in the world</Description>
     <Price>$1.1</Price>
</Item>

Let’s do our first modification. We need to change the existing data of the XML file. The PHP code snippet to do this can be written as follows.

$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$result = $xpath->query("/Shop/ItemList/Item");

$result->item(0)->getElementsByTagName('Price')->item(0)->nodeValue = '$1.2';
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$xml = $dom->saveXML();

$dom = new DOMDocument;
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('Item');
foreach ($items as $item) {
    if($item->hasChildNodes()){

        //Print the item codes
        echo 'Item Code : ' . $item->childNodes->item(1)->nodeValue;
        echo '<br>';

        //Print the item Names        
        echo 'Item Name : ' . $item->childNodes->item(3)->nodeValue;
        echo '<br>';
        //Print the item Descriptions        
        echo 'Item Description : ' . $item->childNodes->item(5)->nodeValue;
        echo '<br>';
        //Print the item Prices        
        echo 'Item Price : ' . $item->childNodes->item(7)->nodeValue;
        echo '<br><br>';
    } 
}

Copy and pate the above two code snippets in order on the PHPcodepad and check the results. You will see the details of three items in our item list as follows. Note that the price of the first pencil has changed from $1 to $1.2.

   Item Code : 1
   Item Name : Pencil - 9H
   Item Description : 9H - Hardest pencil available in the world
   Item Price : $1.2

   Item Code : 2
   Item Name : Pencil - F
   Item Description : 9H - Medium pencil available in the world
   Item Price : $0.8

   Item Code : 3
   Item Name : Pencil - 9B
   Item Description : 9H - Softest pencil available in the world
   Item Price : $0.6

Now we will discuss how it is working. Referring to the second code snippet, first we create an instance of DOMDocument class and then we load our XML file into our new DOMDocument object. An instance of DOMXPath is created to query the XML file. Since we have to change the details of an item, we query for “/Shop/ItemList/Item”. This gives us a DOMNodeList containing all matching item nodes. Then we read the first item and set the price as follows.

$result->item(0)->getElementsByTagName('Price')->item(0)->nodeValue = '$1.2';

Then as the final step, we save the changes made for the XML file. With that, our first task is completed.

So, now we will move into our second task. We need to add a new pencil right after the first pencil. Let me show you the code snippet first for this purpose.

$dom = new DOMDocument;
$dom->loadXML($xml);
$result = $dom->getElementsByTagName('ItemList')->item(0);

$child = $dom->createElement('Item');
$subChildId = new DOMElement('Id', 4);
$subChildName = new DOMElement('Name', 'Pencil - 8H');
$subChildDescription = new DOMElement('Description', '8H - Second hardest pencil available in the world');
$subChildPrice = new DOMElement('Price', '$1.1');
$child->appendChild($subChildId);
$child->appendChild($subChildName);
$child->appendChild($subChildDescription);
$child->appendChild($subChildPrice);
if (is_object($result)) {
 $result->appendChild($child);
}
$xmlResult = $dom->saveXML();

$dom = new DOMDocument;
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('Item');
foreach ($items as $item) {
    if($item->hasChildNodes()){

        //Print the item codes
        echo 'Item Code : ' . $item->childNodes->item(1)->nodeValue;
        echo '<br>';

        //Print the item Names        
        echo 'Item Name : ' . $item->childNodes->item(3)->nodeValue;
        echo '<br>';
        //Print the item Descriptions        
        echo 'Item Description : ' . $item->childNodes->item(5)->nodeValue;
        echo '<br>';
        //Print the item Prices        
        echo 'Item Price : ' . $item->childNodes->item(7)->nodeValue;
        echo '<br><br>';
    } 
}

Read a XML File from PHP

“Hi, in this post I’m going to explain how we can read a XML file from PHP and give you an example for the same. When we start working with XML for the first time, it is difficult to understand how we can manipulate a XML file. I use the DOMDocument to manipulate the XML file which I show in the following example. You can use PHPcodepad to test the example which I’m discussing here. I hope this post will be useful for you!”

Let’s assume we have the following XML file.

$xml = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
    <Shop>
        <ItemList>
             <Item>This
                 <Id>1</Id>is
                 <Name>Pencil - 9H</Name>the
                 <Description>9H - Hardest pencil available in the world</Description>first
                 <Price>$1</Price>pencil in the list.
             </Item>
             <Item>This
                 <Id>2</Id>is
                 <Name>Pencil - F</Name>the 
                 <Description>9H - Medium pencil available in the world</Description>second 
                 <Price>$0.8</Price>pencil in the list. 
             </Item>
             <Item>This
                 <Id>3</Id>is
                 <Name>Pencil - 9B</Name>the
                 <Description>9H - Softest pencil available in the world</Description>third
                 <Price>$0.6</Price>pencil in the list.
             </Item>
             <Item/>
         </ItemList>
     </Shop>
XML;

Now let us write a PHP code snippet to read item details in the above XML file.

$dom = new DOMDocument;
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('Item');
foreach ($items as $item) {
    if($item->hasChildNodes()){

        //Print the item codes
        echo 'Item Code : ' . $item->childNodes->item(1)->nodeValue;
        echo '<br>';

        //Print the item Names        
        echo 'Item Name : ' . $item->childNodes->item(3)->nodeValue;
        echo '<br>';
        //Print the item Descriptions        
        echo 'Item Description : ' . $item->childNodes->item(5)->nodeValue;
        echo '<br>';
        //Print the item Prices        
        echo 'Item Price : ' . $item->childNodes->item(7)->nodeValue;
        echo '<br><br>';
    } 
}

Copy and pate the above two code snippets in order on the PHPcodepad and check the results. You will see the details of three items in our item list as follows.

   Item Code : 1
   Item Name : Pencil - 9H
   Item Description : 9H - Hardest pencil available in the world
   Item Price : $1

   Item Code : 2
   Item Name : Pencil - F
   Item Description : 9H - Medium pencil available in the world
   Item Price : $0.8

   Item Code : 3
   Item Name : Pencil - 9B
   Item Description : 9H - Softest pencil available in the world
   Item Price : $0.6

Now we will discuss how it is working. Referring to the second code snippet, first we create an instance of DOMDocument class and then we load our XML file into our new DOMDocument object. Since we need to list all our item details, we read all the “Item” XML tags. Then inside the foreach loop, we iterate through each “Item” tag and display the item details as necessary.

Notice how we access the each child node’s value. Have you noticed that the index we use is an odd value (1, 3, 5, 7).  Do you understand why is it? The following PHP code snippet will give you the answer for that question.

$dom = new DOMDocument;
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('Item');
foreach ($items as $item) {
    if($item->hasChildNodes()){

        echo $item->childNodes->item(0)->nodeValue . " " . $item->childNodes->item(2)->nodeValue . " " . 
             $item->childNodes->item(4)->nodeValue . " " . $item->childNodes->item(6)->nodeValue . " " . 
             $item->childNodes->item(8)->nodeValue;
        echo '<br>';
    } 
}

You will notice the following result.

   This is the first pencil in the list.
   This is the second pencil in the list.
   This is the third pencil in the list. 

Notice how we access the data in between “Item”  tag and which are not within each child tag. Have you noticed that the index we use is an even value (0, 2, 4, 6, 8).

I hope now you have a clear idea to properly read a XML file in PHP.

We will meet again in another post soon!