Save array as xml

前端 未结 3 1881
再見小時候
再見小時候 2021-01-13 06:55
array(
name => text,
surname => text,
country => text,
date => text
)

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

3条回答
  •  借酒劲吻你
    2021-01-13 07:37

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

提交回复
热议问题