将数组保存为xml文件

时间:2014-03-07 08:53:40

标签: php xml simplexml

我用php-code保护了函数:

$replaceData = array(
        '%userName%' => $order->getUserFullName(),
        '%userEmail%' => $order->getUserEmail(),
        '%userPhone%' => $order->getUserPhone(),
        '%userDeliver%' => $order->getUserDeliverTo(),
        '%orderId%' => $order->getId(),
        '%orderKey%' => $order->getKey(),
        '%orderLink%' => shop_url('cart/view/' . $order->getKey()),
    );

如何使用simpleXML将此数组保存到xml文件?

1 个答案:

答案 0 :(得分:1)

尝试这样做:

$replaceData = array(
        '%userName%' => $order->getUserFullName(),
        '%userEmail%' => $order->getUserEmail(),
        '%userPhone%' => $order->getUserPhone(),
        '%userDeliver%' => $order->getUserDeliverTo(),
        '%orderId%' => $order->getId(),
        '%orderKey%' => $order->getKey(),
        '%orderLink%' => shop_url('cart/view/' . $order->getKey()),
    );

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($replaceData, array ($xml, 'addChild'));
print $xml->asXML();

更正,请尝试将其另存为xml

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

}
$doc->save('file.xml');