创建 xml 文件 [英] creating xml file
本文介绍了创建 xml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建如下的 xml 文件,有人可以帮助如何使用 php 获取它吗?
I am creating xml file as below, can anybody help how to get that using php?
xml 文件:
<products>
<product id="123" />
</products>
php 文件:
我正在使用以下代码但没有得到如上的结果
i am using following code but not getting result as above
$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";
}
推荐答案
您没有得到想要的结果,因为您将 id
添加为标签而不是属性.我只是稍微重构了您的代码并将 id
设为一个属性.我测试了下面的代码,它产生了你想要的结果.
You are not getting the results you want because you're adding id
as a tag rather than an attribute. I just refactored your code a little and made id
an attribute. I tested the code below and it produces your desired result.
<?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");
?>
这篇关于创建 xml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文