我有以下代码来创建XML文件
<?php
try
{
$dom = new domDocument;
$dom->formatOutput = true;
$root = $dom->appendChild($dom->createElement( "items" ));
$sxe = simplexml_import_dom( $dom );
$sxe->addChild("model", "HTC Desire");
$sxe->addChild("model", "Motorola Atrix");
echo $sxe->asXML();
}
catch( Exception $e )
{
echo $e->getMessage();
}
?>
执行此代码时,它会生成以下内容:
<?xml version="1.0"?>
<items>
<model>HTC Desire</model>
<model>Motorola Atrix</model>
</items>
但是,我想为每个模型包含一个名为item
的元素,结果应为:
<?xml version="1.0"?>
<items>
<item><model>HTC Desire</model></item>
<item><model>Motorola Atrix</model></item>
</items>
任何人都可以建议如何做到这一点?
答案 0 :(得分:0)
addChild方法返回一个SimpleXMLElement对象,表示添加到XML节点的子对象。这允许方法链接如下:
try
{
$dom = new domDocument;
$dom->formatOutput = true;
$root = $dom->appendChild($dom->createElement( "items" ));
$sxe = simplexml_import_dom($dom);
$sxe->addChild("item")->addChild("model", "HTC Desire");
$sxe->addChild("item")->addChild("model", "Motorola Atrix");
echo $sxe->asXML();
}
catch( Exception $e )
{
echo $e->getMessage();
}