【问题标题】:Remove a xml node in php在php中删除一个xml节点
【发布时间】:2011-03-07 15:53:39
【问题描述】:

我的 xml 文件:

<temporary>
  <users>
    <temp>
      <id>1</id>
      <title> Undercover</title>
      <author>Wiwit</author>
    </temp>
    <nissi>
      <confirm>3977678bce8515e8cdbfa64850904ad1</confirm>
      <firstname>hi</firstname>
      <lastname>hhey</lastname>
      <day>1</day>
    </nissi>
   </users>
</temporary>

我的 php:

<?php
$user="nissi";
$xml = simplexml_load_file("temporary.xml") 
       or die("Error: Cannot create object");
unset($xml->temporary->users->$user);
?>

为什么这不起作用。 取消设置不起作用。节点不会被删除。

【问题讨论】:

  • 什么失败了?文件加载还是unset()调用?

标签: php xml simplexml


【解决方案1】:

它是这样工作的:

$user="nissi";
$xml = simplexml_load_file("temporary.xml") 
       or die("Error: Cannot create object");
unset($xml->users->$user);
echo $xml->asXML();

您不能在此处的“请求”temporary 中获取 xml 的根。

DEMO HERE

【讨论】:

  • 没错!使用 $xml 对象来证明!
  • 只要调用与根节点同名的变量,就可以防止这种混淆。
  • @Josh Davis : 这对初学者来说是一个很好的建议 :)
  • 是的,这几乎是我能给任何 SimpleXML 用户的最好建议 :) 那,而且他们不认为 SimpleXMLElement 是某种可以使用print_r() 检查的数组但是那个有点太神秘了。
【解决方案2】:

你不能单独使用 SimpleXML,你必须使用 DOMElement 转换,如下所述:

Remove a child with a specific attribute, in SimpleXML for PHP

【讨论】:

  • 确实如此。但是在这里,他的 XML 中没有属性 :)
猜你喜欢
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2012-04-19
  • 2018-03-01
  • 2017-09-13
  • 2014-04-05
相关资源
最近更新 更多