Posts Tagged ‘xml’

XML to Array and Array to Xml in CakePHP

October 19th, 2009

When working with xml allot, you’ll find that this little ‘trick’ might come in handy.

Editing large xml structures is a pain. So why not convert them to a nice array?

It’s done like this:
The xml:

<PipeMsg>
    <Header>
        <Task>Logon</Task>
	<AuthenticationToken>sdfdg4-hkjty45-4544-sdfdsf4</AuthenticationToken>
	<CreationDstamp>54641215</CreationDstamp>
    </Header>
    <Body>
	<UserName>Crazy</UserName>
	<Password>cinderella </Password>
    </Body>
</PipeMsg>

Now convert to an array:

$objXml = 'the xml in the blok above';
$arrXml = Set::reverse($objXml;);
 
echo $arrXml['Header']['Task'];
//result
Logon

We can also go the other way around, in CakePHP we do it like this:

//$arrXml = array from example above
App::Import('Helper', 'Xml');
$objXmlHelper = new XmlHelper();
$objXml = $objXmlHelper->serilize($arrXml);

Parse CDATA with SimpleXML

October 17th, 2009

When trying to parse xml with php’s SimpleXml you’ll notice that the SimpleXmlElement comes up empty.

Say you have the following xml structure:

<root>
    <username>
        <![CDATA[     Text you want to escape goes here...   ]]>
   </username>
</root>

When parsing that with SimpleXml the end result will simply be an empty tag:

<root>
    <username>
   </username>
</root>

To solve this you need to supply “LIBXML_NOCDATA” as parameter to the “simplexml_load_file function“, like this:

$objXml = simplexml_load_file($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

Now the CDATA will be converted into normal strings.

When not reading the xml from a file, but if it comes from a xml post(an api for example), the same applies:

$objXml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

Note, the LIBXML_NOCDATA can not be used when doing the following:

$ojbXml = new SimpleXmlElement($xml);