创建xml文件

时间:2011-05-13 02:48:56

标签: php xml

我正在创建如下的xml文件,有人可以帮助如何使用php获取它吗?

xml文件:

<products>
<product id="123" />
</products>

Php文件:

我正在使用以下代码但未获得上述结果

$xml = new DomDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$products= $xml->createElement('products');
$product = $xml->createElement('product');
$id = $xml->createElement('id');
$xml->appendChild($products);
$products->appendChild($product);
$product->appendChild($id);
$id->nodeValue = 123; 
$xml->save("data.xml");

检索xml数据:

         $xml = new DomDocument();
         $xmlFile = "data.xml";
         $xml= DOMDocument::load($xmlFile);
         $product = $xml->getElementsByTagName("product");             
         foreach($product as $node) 
            { 
        $address = $node->getElementsByAttributeName("address");
        $address = $address->item(0)->nodeValue;
          echo"$address";
            }

2 个答案:

答案 0 :(得分:2)

您无法获得所需的结果,因为您要将id添加为标记而非属性。我只是稍微重构了你的代码并使id成为一个属性。我测试了下面的代码,它产生了你想要的结果。

<?php
$xml = new DomDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$products= $xml->createElement('products');
$product = $xml->createElement('product');
$xml->appendChild($products);
$products->appendChild($product);
$product->appendChild(new DomAttr('id', '123'));
$xml->save("data.xml");
?>

答案 1 :(得分:0)

如果要将id作为属性,则需要使用DOMElement::setAttribute()方法。我认为这将有效 - ccording to the documentation,如果某个属性尚不存在,则会创建它。

$product->setAttribute("id", "123");

然后去$product->appendChild( $id );