How to read and manipulate an XML document with PHP

Here’s our XML document representing a fictional SOAP service.

We need to accomplish two tasks:

  1. Read the current value of the ovCollCurrency node
  2. Set the ovCollCurrency to the value that we desire

Let’s get into it.

The script starts by checking to see if the XML file exists in the current directory:

if (file_exists('test.xml')) {
   // process here
}

If the file exists, we use the simplexml_load_file() function to load and parse our test.xml file into an object. That enables us to traverse through the nodes of the XML document.

$xml = simplexml_load_file('test.xml');

Imagine we need to read the value (LKR) of the ovCollCurrency node. In our XML document, we could see that ovCollCurrency is a child of the pReceipt node. The pReceipt node is, in turn, a child of the bfnReceiptSrvRequest node. The bfnReceiptSrvRequest is also a child node of the Body node. The Body node lives under the ‘soapenv‘ namespace. bfnReceiptSrvRequest lives under the ‘int‘ namespace. All child nodes of the pReceipt node live under the ‘typ‘ namespace. With that understanding, now we can build a statement that can traverse through the document to reach the ovCollCurrency node:

Here’s how to do it:

As you can see in the above statement, getting access to the pReceipt node gives us access to all of its child nodes.

Now that we have access to the value of ovCollCurrency. How can we set the value of a node?

If you’ve looked at the above statement carefully, you could see that we’ve used an ampersand (&) just before the $xml-> statement. What it does is giving us a reference to the respective object in the memory tree. With that reference, now we can directly manipulate our DOM tree in the memory to update the particular node we want.

To update the value of ovCollCurrency in this case, we can simply run the below statement:

$pReceipt->ovCollCurrency = 'EURO';

To make sure whether the change has taken an effect on the DOM tree, you can traverse through the DOM to the ovCollCurrency node and echo out its contents:

Here’s the full script:

Was this helpful?
+1
0
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0