2011-05-13 101 views
3

我创建xml文件如下,任何人都可以帮助如何使用PHP?创建xml文件

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

你不是 得到你想要的结果,因为你将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

是的,它正是我想要的。但如果我想在创建xml文件后回显“id”值,那么在加载xml文件后应该做什么修改 – rick 2011-05-13 03:39:36

+0

@rick:您可以在末尾添加'echo $ product-> getAttribute('id');'行我的示例代码来回显'id'。 – Asaph 2011-05-13 03:42:32

+0

我已经给出了上面的'检索XML数据'的例子,我可以用我的例子中的这条线......对不起,我是xml的新手 – rick 2011-05-13 03:50:37

0

如果id是成为一个属性,那么你需要使用DOMElement::setAttribute()方法。我认为这将起作用 - ccording to the documentation,如果一个属性不存在,它将被创建。

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

然后协议书的$product->appendChild($id);