php - 创建 xml 文件

标签 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";
            }

最佳答案

您没有得到想要的结果,因为您将 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/

相关文章:

php - _SESSION ['xxx' ] 未在我的 Web 应用程序中跨页面保留

用于编辑 XML/XSL 的 .NET Windows 控件?

java - 如何使用JAXB解析xml?

xml - XSD:检查是否存在具有特定值的元素

javascript - 需要使用jquery提取XML节点,其中节点的sibling等于某个值;现在使用 xPath

php - 如何在不知道键值的情况下在php中读取JSON数据

php - 公司如何发送远程通知?

javascript - 如何通过 Ajax 将 PHP 输出返回到页面?

PHP MYSQL 获取带有新行的文本

xml - 使用具有多个属性的 scala-xml API 进行解析