// 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;
}
Run Code Online (Sandbox Code Playgroud)
使用SimpleXML
对于#1(如在如何将数组转换为SimpleXML中)
<?php
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML("file.xml");
Run Code Online (Sandbox Code Playgroud)
#2
$xml_data_as_object = simplexml_load_file("file.xml")
Run Code Online (Sandbox Code Playgroud)
返回xml数据的对象表示.
将对象转换为数组:
$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
);
}
Run Code Online (Sandbox Code Playgroud)