2012-07-27 74 views
0

您好!PHP XML:根據節點值去除元素和所有的孩子?

我有一個問題,林根據一個孩子值試圖刪除元素(孩子的): 這裏是XML示例:

<?xml version="1.0" encoding="UTF-8"?> 
    <Businesses> 
    <Business NAME="busin1"> 
    <CHILD ID="30"><title>child Title</title> 
    <description>Child Description</description> 
    <urlToSite>http://www.MySite.co.il</urlToSite> 
    <endtime>20120720103000</endtime> 
    <starttime>20120710191500</starttime> 
    </CHILD> 
<CHILD>...</CHILD> 
<CHILD>...</CHILD> 
</Business> 
    </Businesses> 

現在我需要刪除所有特定的「兒童「元(已包含兒童),其‘結束時間’值是舊的,然後現在(或簡稱‘結束時間’等於特定值)

‘結束時間’與格式的日期:YYYYMMDDHHMMSS

這裏我的第一次嘗試(沒有成功):

$doc = new DOMDocument; 
    $doc->load('MyXML.xml'); //The XML Above 

    $thedocument = $doc->documentElement; 

    //this gives you a list of the childs 
    $list = $thedocument->getElementsByTagName('CHILD'); 

    //figure out which ones you want -- assign it to a variable (ie: $nodeToRemove) 
    $nodeToRemove = null; 
$time=date("YmdHis",time()); 
    foreach ($list as $domElement){ 
$attrValue = $domElement->childNodes->item('endtime')->nodeValue; //not Sure about this!! 
     if ($attrValue > $time) { 
     $nodeToRemove = $domElement; 
     } 
    } 

    //Now remove it. 
    if ($nodeToRemove != null) 
    $thedocument->removeChild($nodeToRemove); 
    echo $doc->saveXML(); 

非常感謝!

回答

0

再次嗨!

的研究。最後我找到了問題的一整天之後..

首先謝謝邁克爾的幫助。

下面是最終和工作代碼:

<?php 

$doc = new DOMDocument; 
$doc->load('MyXML.xml'); 

$maxTime = date("YmdHis", time()); 

$xpath = new DOMXPath($doc); 
$q = "/Businesses/Bisiness/CHILD/endtime[. < {$maxTime}]"; 
foreach ($xpath->query($q) as $node) { 
    $businessNode = $node->parentNode; 
    $businessesNode = $businessNode->parentNode; 
    $businessesNode->removeChild($businessNode); 
} 

// inserting to variable ONLY 
$last = $doc->saveXml(); 
// IMPORTANT!! - we have to rewrite to XML the Results back!! 
file_put_contents('MyXML.xml', $last) 
?> 

我沒有帶發現了它的任何地方,所以我希望這將幫助你..再次:)

1

使用XPath查詢文檔節點。試試這個:

$maxTime = date("YmdHis", time()); 

$doc = new DOMDocument(); 
$doc->load("MyXML.xml"); 

$xpath = new DOMXPath($doc); 
$q = "/Businesses/Bisiness/CHILD/endtime[. > {$maxTime}]"; 
foreach ($xpath->query($q) as $node) { 
    $businessNode = $node->parentNode; 
    $businessesNode = $businessNode->parentNode; 
    $businessesNode->removeChild($businessNode); 
} 

Here's XPath的一個很好的例子。

+0

嗨!我試過你的代碼,它仍然無法正常工作:(我無法理解爲什麼...我在你的代碼中發現的唯一問題是> {$ maxTime}應該是<{$ maxTime}它找到正確的CHILD ID(我添加了:「echo $ businessNode-> getAttribute('ID');」我可以看到正確的CHILD ID,但它不會將它從節點中刪除,我添加了「echo $ doc-> saveXml() ;「最後以及...任何建議??謝謝! – EranLevi 2012-07-28 14:23:19