PHP使用dom删除多个元素 [英] PHP remove multiple elements with dom

查看:67
本文介绍了PHP使用dom删除多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DOM Document删除php中的多个元素,但是它无法正常工作,因为我希望它能正常工作。

I'm trying to remove multiple elements in php using DOM Document, but it does not work as i wanted it to work.

<iPhone>
<enAttentePush>
  <UDID>dd6fc8032f0bf4c4b3a9c60f523900c9ad463b620a83b6473eda9a12b2c9d47f</UDID>
  <Message>someDataHere</Message>
</enAttentePush>

<enAttentePush>
  <UDID>dd6fc8032f0bf4c4b3a9c60f523900c9ad463b620a83b6473eda9a12b2c9d47f</UDID>
  <Message>someDataHere</Message>
</enAttentePush>
</iPhone>

我想循环到我的xml文档中,然后擦除所有元素以得到一个空文件。

I want to loop into my xml document and then erase all element to get an empty file.

这是我在php中所做的事情:

Here is what i do in php :

$doc = new DOMDocument;

$doc->load('$myFile'); 
$domNodeList = $doc->getElementsByTagName('enAttentePush'); 
$arraySeen = array(); 
$arrayBug = array(); 

foreach ($domNodeList as $domElement)
{
        //echo('loop / ');
  $tempArray = array(); 

  $aps = $domElement->getElementsByTagName('Message')->item(0)->nodeValue;
  $udid = $domElement->getElementsByTagName('UDID')->item(0)->nodeValue; 
  if (!in_array($udid, $arraySeen))
  {         
      $tempArray[]=$aps; 
      $tempArray[]=$udid; 
      $arrayBug[]=$tempArray;
     $arraySeen[]=$udid; 
   }

   echo("-- removed -- ");
   $domElement->parentNode->removeChild($domElement); 
  }

它仅删除一个节点,通常删除最后一个节点。

It only delete only one node, the last one in general.

我怎么做才能以我的节点为单位循环,并在每次看到节点时将其删除?

How can i do to loop thought my node and remove it each time i see a node ?

非常感谢。

推荐答案

我必须这样做就在最近我的网站上,您发现如果将数组中的元素排队,那么之后就可以很容易地将它们全部删除。这是一个有用的小片段,希望对您有所帮助:

I had to do this just recently on my own site and found that you if you queue up your elements in an array, you can remove them all quite easily after that. Here is a little snippet that use, hopefully it helps you out:

$doc = new DOMDocument;

$doc->load('$myFile');
$domNodeList = $doc->getElementsByTagName('enAttentePush');

$domArray = array(); //set up an array to catch all our nodes

foreach($domNodeList as $dom) {
    $domArray[] = $dom;
}

// loop through the array and delete each node
foreach($domArray as $node){ 
    $doc->documentElement->removeChild($node);
}

$doc->save('$myFile');

这篇关于PHP使用dom删除多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆