Is simpleXML installed?
It should be there by default with php, but it seems to be omitted in some installs (e.g. V7 PHP on ubuntu)
//Make sure simplexml is installed (it should be there by default with php, but it seems to be omitted in some installs.
if (!function_exists('simplexml_load_file'))
die('Server config issue - simpleXML functions are not available.'); //You can install this on ubuntu using: sudo apt-get install php-xml
Read values
For example, this XML file:
<RootElement>
<MyXmlChildName>1234</MyXmlChildName>
</RootElement>
Reading a value:
$xml = simplexml_load_file($_SERVER['DOCUMENT_ROOT'] . "/my_folder/my_file_name.xml");
if ($xml !== False) //Was file loaded OK?
{
if (isset($xml->MyXmlChildName)) //Check child exisrts
echo $xml->MyXmlChildName . "<br>"; //Get its value
}
Read XML to array example
//OPEN OUR XML FILE AND GET THE EXCHANGE RATES
$output = array();
$xml = simplexml_load_file('exchangeRates.xml');
if ($xml !== False) //Was file loaded OK?
{
foreach ($xml as $key => $value) {
//echo $key . "-" . $value . "<br>";
$output[$key] = (string)$value;
}
}
Write XML File
$currentTimestamp = date('Y-m-d H:i:s');
//Create XML file
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
$xml->addChild('ratesLastUpdated', $currentTimestamp);
//$xml->asXml('exchangeRates.xml'); //<<This won't format the XML doc nicely with line breaks
// Save the merged XML to the output file with formatting:
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$dom->save('exchangeRates.xml');
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.