SimpleXml save formated output

When using the SimpleXml->asXML(‘file.xml’) the output is simply written onto one line.

<?xml version="1.0" encoding="UTF-8"?>

There is nothing wrong with this but if you add line breaks and indentations the xml file looks better and is easier to (manually) read.
Unfortunately there is no way to do this using SimpleXML, but there is a quick and dirty way to do this; and that is to import the SimpleXMLobject to a DOMElement and do it there so some example code

$xmlDom = dom_import_simplexml($simpleXmlObject);
$xmlDom->formatOutput = true;

This would result in an xml file looking like this:

<?xml version="1.0" encoding="UTF-8"?>

Easier to read but takes some extra space on the disk (might not be much but it is good to remember).

SimpleXML tags with – in the name

Sometimes a xml file will have tags with “-“s in the name.
It is not to hard to parse this using simplexml, just use the tagname inside curly brackets like: “{tag-name}”

<?xml version="1.0" encoding="utf-8"?>
<medprod xmlns:npl="urn:schemas-instance" version="129">
    <mpa_status xmlns:mpa="urn:schemas-mpa" datastatus="valid" procstatus="reviewed"/>
  <mpa_pharmaceutical-form-group-lx xmlns:mpa="urn:schemas-mpa" v="OSD"/>

Let’s assume we load the above in a SimpleXML object called $simplemedprodXml

$simplemedprodXml= simplexml_load_string($xmlString);
echo (string)$simplemedprodXml['version'];
echo (string)$simplemedprodXml->statuses->mpa_status['datastatus'];
echo (string)$simplemedprodXml->statuses->mpa_status['procstatus'];
echo (string)$simplemedprodXml->{'mpa_pharmaceutical-form-group-lx'}['v'];