How to Convert Array to Simplexml

How to convert array to SimpleXML

a short one:

<?php

$test_array = array (
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();

results in

<?xml version="1.0"?>
<root>
<blub>bla</blub>
<bar>foo</bar>
<overflow>stack</overflow>
</root>

keys and values are swapped - you could fix that with array_flip() before the array_walk. array_walk_recursive requires PHP 5. you could use array_walk instead, but you won't get 'stack' => 'overflow' in the xml then.

PHP convert Array to XML

Almost had it! You simply had to pass the $subnode, not $xml into the recursive call of function:

// XML BUILD RECURSIVE FUNCTION
function array_to_xml($array, &$xml) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml->addChild($key);
array_to_xml($value, $subnode);
} else {
array_to_xml($value, $subnode);
}
} else {
$xml->addChild($key, $value);
}
}
}

// EXAMPLE ARRAY
$newArray = array(
"Project" =>
array("ExternalProjectID" => 53,
"ProjectName" => "Doon Creek",
"Location" =>
array ("Address" => "123 Fake Street",
"City" => "Toronto",
"Province" => "ON",
"Latitude" => 43.0000,
"Longitude" => -80.0000),
"Website" =>
"http://www.website.com/our-communities.php?newcommunity=53",
"ContactInformation" =>
array("ContactPhone" => "555-5555",
"ContactEmail" => "email@email.com",
"SalesOfficeAddress" => "123 Fake Street",
"SalesOfficeCity" => "Toronto",
"SalesOfficeProvince" => "ON")
)
);

// CREATING XML OBJECT
$xml = new SimpleXMLElement('<Projects/>');
array_to_xml($newArray, $xml);

// TO PRETTY PRINT OUTPUT
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
$domxml->loadXML($xml->asXML());

echo $domxml->saveXML();

Output

<?xml version="1.0"?>
<Projects>
<Project>
<ExternalProjectID>53</ExternalProjectID>
<ProjectName>Doon Creek</ProjectName>
<Location>
<Address>123 Fake Street</Address>
<City>Toronto</City>
<Province>ON</Province>
<Latitude>43</Latitude>
<Longitude>-80</Longitude>
</Location>
<Website>http://www.website.com/our-communities.php?newcommunity=53</Website>
<ContactInformation>
<ContactPhone>555-5555</ContactPhone>
<ContactEmail>email@email.com</ContactEmail>
<SalesOfficeAddress>123 Fake Street</SalesOfficeAddress>
<SalesOfficeCity>Toronto</SalesOfficeCity>
<SalesOfficeProvince>ON</SalesOfficeProvince>
</ContactInformation>
</Project>
</Projects>

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
* function xml2array
*
* This function is part of the PHP manual.
*
* The PHP manual text and comments are covered by the Creative Commons
* Attribution 3.0 License, copyright (c) the PHP Documentation Group
*
* @author k dot antczak at livedata dot pl
* @date 2011-04-22 06:08 UTC
* @link http://www.php.net/manual/en/ref.simplexml.php#103617
* @license http://www.php.net/license/index.php#doc-lic
* @license http://creativecommons.org/licenses/by/3.0/
* @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
*/
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

How to convert Array to XML in php

You're missing the else block.
After this code:

if(is_array($value)) {
echo '<',$value,'>',htmlentities($value),'</',$value,'>';
........
}

add this:

} else {
echo $value;
}

Also I would recommend writing a recursive function to be able to use arrays of any depth.

How can i convert array to SimpleXMLElement Object

$xml = '<?xml version='1.0' standalone='yes'?>';
function rekursiveArrayToXML($array, &$xml, $name = 'root') {
$xml .= "$<$name";
if (is_array($array) AND isset($array['@attributes'])) {
foreach ($array['@attributes'] as $k => $v) {
$xml .= " $k=\"$v\"";
}
unset($array['@attributes']);
}
$xml .= ">";
if (is_array($array)) {
foreach ($array as $k => $v) {
rekursiveArrayToXML($v, $xml, $k);
}
} else {
$xml .= $array;
}
$xml .= "</$name>\n";
}

$array = array(
'@attributes' => Array
(
'Id' => 925343664,
'FloorplanID' => 617454,
'BuildingID' => 0
),
'Unit' => Array(),
'Comment' => Array(),
'Availability' => Array
(
'VacancyClass' => 'Occupied',
'MadeReadyDate' => Array
(
'@attributes' => Array
(
'Month' => 1,
'Day' => 24,
'Year' => 2016,
)

)

)
);

rekursiveArrayToXML($array, $xml);

var_export(simplexml_load_string($xml));

something like that ;)

Converting a PHP array to XML?

Some working Example for the Data in Question that is on-site: https://stackoverflow.com/a/14143759/367456

Original answer follows:

Take a look at these pre-defined implementations:

http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/

http://vantulder.net/f2o/notities/arraytoxml/

How to convert array to xml

Data :

 $cities = array(
array(
'cityId' => 1,
'stateId' => 217,
'cityName' => 'New York'
),
array(
'cityId' => 2,
'stateId' => 0,
'cityName' => 'Paris'
),
);

This :

$xml = new SimpleXMLElement('<data/>');
foreach ($cities as $key => $city)
{
$xml->city[$key]['cityId'] = $city['cityId'];
$xml->city[$key]['stateId'] = $city['stateId'];
$xml->city[$key]['cityName'] = $city['cityName'];
}

OR (better) :

xml = new SimpleXMLElement('<data/>');
foreach ($cities as $cityData)
{
$city = $xml->addChild('city');
$city->addAttribute('cityId', $cityData['cityId']);
$city->addAttribute('stateId', $cityData['stateId']);
$city->addAttribute('cityName', $cityData['cityName']);
}

Will output :

<data>
<city cityId="1" stateId="217" cityName="New York" />
<city cityId="2" stateId="0" cityName="Paris" />
</data>


Related Topics



Leave a reply



Submit