【问题标题】:creating xml file创建xml文件
【发布时间】:2011-05-13 02:48:55
【问题描述】:

我正在创建如下的 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";
            }

【问题讨论】:

    标签: php xml


    【解决方案1】:

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

    【讨论】:

    • 是的,这正是我想要的。但如果我想在创建 xml 文件后回显“id”值,那么在加载 xml 文件后我应该做哪些更改
    • @rick:您可以在我的示例代码末尾添加行echo $product-&gt;getAttribute('id'); 以回显id
    • 我已经在上面给出了“检索 xml 数据”的例子,我可以在我的例子中使用你的这一行吗......对不起,我是 xml 新手
    • @rick:看起来您正在阅读的 xml 文档的结构不同。原始 xml 有 &lt;products&gt;&lt;product&gt;,而你的读者有 &lt;marker&gt;&lt;address&gt;。他们看起来不兼容。无论如何,请发布一个新问题而不是更改这个问题。谢谢。
    【解决方案2】:

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

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

    然后loas $product-&gt;appendChild( $id );

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 2012-12-29
      • 2019-06-06
      • 2021-08-19
      • 2011-07-19
      相关资源
      最近更新 更多