【问题标题】:How to insert data in xml file using php?如何使用php在xml文件中插入数据?
【发布时间】:2011-05-31 19:37:42
【问题描述】:
<?xml version="1.0" encoding="UTF-8"?>
<root></root>

这是我的 xml 文件。我想在标签之间使用 dom 方法插入更新数据。我是 php 和 Xml 技术的初学者。我成功地创建并读取了这个文件,但无法使用 php 在其中输入数据。

创建代码如下:-

  $doc = new DOMDocument('1.0', 'UTF-8');
  $ele = $doc->createElement( 'root' );
  $ele->nodeValue = $uvar;
  $doc->appendChild( $ele );
  $test = $doc->save("$id.xml");

阅读代码如下:-

  $xdoc = new DOMDocument( );
  $xdoc->Load("$gid.xml");
  $candidate = $xdoc->getElementsByTagName('root')->item(0);
  $newElement = $xdoc ->createElement('root');
  $txtNode = $xdoc ->createTextNode ($root);
  $newElement -> appendChild($txtNode);
  $candidate -> appendChild($newElement);
  $msg = $candidate->nodeValue;

有人可以帮忙插入和更新吗?谢谢!

【问题讨论】:

  • 你能否把你的问题说得更清楚些。您在哪里获取文本以更新您的 xml,或放置您的最终 XML 结构。

标签: php xml dom insert-update


【解决方案1】:

我对 DOMDocument 类没有太多经验,但使用 simpleXML 对象可能更容易。取件比较快。

http://us.php.net/simplexml

然后你就可以了

$xml = new SimpleXMLElement('<root></root>');
$xml->addChild('test_node_name', 'value');
$xml->test_node_name = 'new_value';
echo $xml->test_node_name;

这样,您可以像对待数组一样对待具有相同名称的多个子元素,这样您就可以遍历它们,或通过索引访问它们。您还可以从文件或字符串创建 simplexml 对象。看看吧。

【讨论】:

    【解决方案2】:

    有时 PHP + XML 可能有点不舒服。大多数时候我发现这段代码很有用(根据你的情况重写了一点):

    $array = array('anxmltag'=>'hello everybody','anothertag'=>'content','lasttag'=>'maybe');
    
    $doc = new DOMDocument('1.0','UTF-8');
    $root = $doc->createElement('root');
    $doc->appendChild($root);
    
    foreach($array as $key=>$value) {
    
        $root->appendChild($dom->createElement($key))->appendChild($dom->createTextNode($value));
    }
    
    $doc->save("$id.xml");
    

    您可能希望扩展此代码以编写二级 XML 标记。

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2014-11-11
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      相关资源
      最近更新 更多