PHP to XML and viceversa Conversions

PHP -> XML :

PHP File:

<?php

//Creates XML string and XML document using the DOM
$dom = new DomDocument(‘1.0’);

//add root – <data>
$data = $dom->appendChild($dom->createElement(‘DATA’));

//add <category> element to <data>
$category = $data->appendChild($dom->createElement(‘category’));

$category->appendChild( 

$dom->createTextNode(‘categoryid’));
//generate xml 

$dom->formatOutput = true; // set the formatOutput attribute of
// domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom->save(‘test1.xml’); // save as file
?>

text1.xml output:

<?xml version=”1.0″?>
<DATA>
<category>categoryid</category>
</DATA>

XML->PHP:

$data_array = (array) simplexml_load_string($string);

foreach ($data_array as $field => $value) {

echo “$field => $value “;

}

Advertisements