2010-09-20 30 views
5
array(
name => text, 
surname => text, 
country => text, 
date => text 
) 

1) Come posso salvare questo array su file come file xml?Salva array come xml

2) Come leggere questo file quindi come matrice?

+1

Hai pensato di usare JSON per serializzare invece? Sono prevenuto contro XML. Troppo grasso = / – NullUserException

risposta

7
// 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; 
} 
5

Utilizzando SimpleXML

per # 1 (come 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"); 

per # 2

$xml_data_as_object = simplexml_load_file("file.xml") 

restituisce una rappresentazione oggetto dei dati XML.

convertire l'oggetto in un array con:

$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 
); 
}