XML (eXtensible Markup Language) is a convenient way of writing human-readable data sets which can also be shared between computer systems that might otherwise be incompatible with each other. PHP is a powerful scripting language with a large and growing user base. By converting an XML file to PHP, you will be able to modify your data in real-time from the server, then use the data in a variety of dynamic applications.
A Simple Example with SimpleXML
Create an XML file named "inventory.xml" in a folder named "includes." It will look something like this:
Save a duplicate copy of your document named "inventory.php." Add the PHP open and closing tags at the beginning and end of this document.
Convert your XML nodes into a string and assign them to a variable named $xmlString. You can do this simply by wrapping your existing XML in a few special characters: at the beginning, three "less than" signs in a row, followed by the letters XML; and after the closing of your root node, the letters XML again. Remember to finish your assignment statement with a semicolon. Your document will now look like this:
Create another document named "display-inventory.php" and save it in the folder one level above your "includes" folder. This script will include your converted XML file, use it to create a SimpleXMLElement object, and read out the node values into paragraphs.
Upload the files to your server and view the file view-inventory.php in your web browser. It will output:
You can make your XML string more dynamic by using variables to set the values of the nodes. Create a variable named $variable with a value of "hex," then read out the variable's value into the
Alternatively, you can load your XML into PHP without converting the file into a string. Upload your original file inventory.xml to your server, and amend your script to read:
Post the revised file to your server, and you should see results similar to the first example.