XML to Array and Array to Xml in CakePHP

October 19th, 2009 by Crazy Leave a reply »

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);
Advertisement

5 comments

  1. NoraMarx says:

    A very nice Topic. Thanks alot hope you go for the detail next time!

  2. Nik Chankov says:

    Good hint! I didn’t knew it especially Array to XML is really good. I had a project which required exactly this, but later on it was transferred to comma separated output. Anyway, good hint!

  3. Crazy says:

    Personally I don’t really like working with CSV, it’s much harder to work with then xml.

    Especially for what I’m using it atm, communication between two sites.

Trackbacks /
Pingbacks

  1. Blogs on a stick
  2. Yahoo News

Leave a Reply

You must be logged in to post a comment.