我正在创建如下 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";
}
最佳答案
您没有得到想要的结果,因为您将 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");
?>
关于php - 创建 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5986763/