dongzhao8233 2013-08-24 13:15
浏览 34

无法从XML文档中删除所有子项(PHP)

Unable to remove all children from the XML document

<?xml version="1.0" encoding="UTF-8"?>
    <routes>
      <route name="admin" />
      <!---->
      <route name="blog" bla bla/>
      <route name="blog" bla bla/>
      <route name="blog" bla bla/>
    </routes>


$xml = simplexml_load_file('routes.xml');

$dom_sxe = dom_import_simplexml($xml); $dom = new \DOMDocument('1.0'); $dom_sxe = $dom->importNode($dom_sxe, true); $dom_sxe = $dom->appendChild($dom_sxe); foreach ($dom->getElementsByTagName('route') as $route) { if($route->getAttribute('name') === 'blog') { $route->parentNode->removeChild($route); echo $route->getAttribute('name'); } } echo $dom->saveXML();

removes only 2 elements with the attribute blog

  • 写回答

1条回答 默认 最新

  • dtuct88226 2013-08-24 14:09
    关注

    The problem is that you are modifying the document while looping through it - a bit like modifying an array in the middle of a foreach loop.

    Note that $dom->getElementsByTagName "returns a new instance of class DOMNodeList" not just an array. So as the loop goes round it is retrieving the elements as it goes; removing one will mess up its assumptions about what exists.

    One solution to this is to copy the entire list of matches into a plain array before you loop over it. There is a built-in function iterator_to_array() which will do just that for you all in one go - basically, it runs a foreach over the iterable object, and collects the values into an array.

    So the simplest (though not necessarily most readable etc) solution is to change this line:

    foreach ($dom->getElementsByTagName('route') as $route)
    

    to this:

    foreach (iterator_to_array($dom->getElementsByTagName('route')) as $route)
    

    Here's a live demo of the fixed code.

    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch