Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save array as xml

Tags:

arrays

php

xml

array(
name => text,
surname => text,
country => text,
date => text
)

1) How can I save this array to file as xml file?

2) How to read this file then as array?

like image 371
James Avatar asked Sep 20 '10 22:09

James


People also ask

Is array supported by XML?

XML provides the capability to display data because it is a markup language. JSON supports array. XML doesn't support array.

What does String could not be parsed as XML mean?

The most likely cause of this error is that the XML data you are trying to process is not valid. Alternatively, the XML data may contain non-standard characters or use a different character set encoding. There are several websites that can validate XML data.


3 Answers

// save
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
foreach($arr as $key=>$value)
{
   $em = $doc->createElement($key);       
   $text = $doc->createTextNode($value);
   $em->appendChild($text);
   $root->appendChild($em);

}
$doc->save('file.xml');
// load
 $arr = array();
 $doc = new DOMDocument();
 $doc->load('file.xml');
 $root = $doc->getElementsByTagName('root')->items[0];
 foreach($root->childNodes as $item) 
 { 
   $arr[$item->nodeName] = $item->nodeValue;
 }
like image 54
a1ex07 Avatar answered Oct 18 '22 19:10

a1ex07


Using SimpleXML

for #1 (as in How to convert array to SimpleXML)

<?php
  $xml = new SimpleXMLElement('<root/>');
  array_walk_recursive($test_array, array ($xml, 'addChild'));
  print $xml->asXML("file.xml");

for #2

$xml_data_as_object = simplexml_load_file("file.xml")

returns an object representation of the xml data.

convert the object to an array with:

$xml_data_as_array = array();
foreach ($xml_data->root as $children) {
   $xml_data_as_array[] = array(
     "name" => $children->name,
     "surname" => $children->surname,
     "country" => $children->country,
     "date" => $children->date
  );
}
like image 29
brian_d Avatar answered Oct 18 '22 17:10

brian_d


Take a look at the Pear module XML::Serializer -- which also includes XML::Unserializer.

http://pear.php.net/package/XML_Serializer/

http://articles.sitepoint.com/article/xml-php-pear-xml_serializer

like image 2
joealba Avatar answered Oct 18 '22 18:10

joealba