2012-12-18 97 views
0

我想从我的xml中删除<wcccanumber>的父节点,如果它的内容符合某个标准,但它只会删除一个节点<wcccanumber>。我如何删除整个父节点?PHP DOM删除孩子

继承人我的代码:

$xml = new SimpleXMLElement('<xml/>'); 

if (file_exists("xml/units/E01.xml")) { 

    $xml = simplexml_load_file("xml/units/E01.xml"); 

    echo "File exists"; 
    echo "</br>"; 

    $wcccanumber = "121202482"; 

    foreach ($xml->call->wcccanumber as $call) { 
     if ($call == $wcccanumber) { 
      $dom = dom_import_simplexml($call); 
      $dom->parentNode->removeChild($dom); 

      $fp = fopen("xml/units/E01.xml","wb"); 
      fwrite($fp,$xml->asXML()); 
      fclose($fp); 
     } 
    } 
} 

这里是XML:

<xml> 
    <call> 
    <wcccanumber>121202482</wcccanumber> 
    <currentcall>FALL</currentcall> 
    <county>W</county> 
    <id>82</id> 
    <location>234 E MAIN ST</location> 
    <callcreated>12:26:09</callcreated> 
    <station>HBM</station> 
    <units>E01</units> 
    <calltype>M</calltype> 
    <lat>45.5225067888299</lat> 
    <lng>-122.987112718574</lng> 
    <inputtime>12/18/2012 12:27:01 pm</inputtime> 
    </call> 
</xml> 
+0

你想删除所有的通话的孩子,对吧? – DanMan

+0

是的,我会,然后我会更多的代码来取代,但我不知道如何删除它们。 –

+0

我最终要删除整个节点,包括调用 –

回答

1

迭代通过call$wcccanumber比较$call->wcccanumber。将$call转换为dom并将其删除(parentNode->removeChild)。

foreach ($xml->call as $call) { 
    if ($call->wcccanumber == $wcccanumber) { 
     $dom = dom_import_simplexml($call); 
     $dom->parentNode->removeChild($dom); 
     $fp = fopen("xml/units/E01.xml","wb"); 
     fwrite($fp,$xml->asXML()); 
     fclose($fp); 
    } 
} 

如果有多个删除是有道理的节省只有一次毕竟缺失已经完成。

$deletionCount = 0; 

foreach ($xml->call as $call) { 
    if ($call->wcccanumber != $wcccanumber) { 
     continue; 
    } 
    $dom = dom_import_simplexml($call); 
    $dom->parentNode->removeChild($dom); 
    $deletionCount++; 
} 

if ($deletionCount) { 
    file_put_contents("xml/units/E01.xml", $xml->asXML()); 
} 
+0

这很有道理。谢谢。我不知道我无法想象我自己... –

+0

有时看不到森林为它的树:) –

+0

嗯,实际上,如果有一个或多个删除,你应该保存*后* foreach',这样你就可以随时保存一次所有的变化。 – hakre