2010-03-14 115 views
0

這裏是我的XML DOM。幫助與DOMDocument類在PHP

 <entities> 
      <entity id="7006276"> 
       <title>xxx</title> 
       <entities> 
        <entity id="7877579"> 
         <title>xxx</title> 
         <entities> 

我想取得編號爲7006276的「實體」,所以我可以訪問它的孩子「實體」爲它創建一些「實體」元素。

我曾嘗試:

$this->xmlDocument = new DOMDocument(); 
// some code creating the above elements (you dont have to care about this comment code...it just creates the above xml structure 
// $this->xmlDocument->createElement('entity'); 
// $sourceEntityElement->appendChild($newEntityElement); 
// and so on... 

// now i want to get the entities mentioned... 
$xmlEntities = $this->xmlDocument->getElementById('7006276')->entities; 

,但它似乎沒有工作。任何想法我如何得到它,所以我可以創建更多'實體'元素?

+0

這個問題有點模糊。請張貼更多的代碼。 – 2010-03-14 04:47:56

回答

1

現在,當您撥打DOMDocument::getElementById時,PHP不知道要查找哪個屬性。根據documentation for getElementById,您需要設置通知PHP關於您的id屬性與DOMElement::setIdAttribute或使用DOMDocument::validate驗證您的文檔與DTD。

1

您可以使用xpath按屬性選擇元素。你將不得不將其轉換爲simplexml並檢查以確保它正確加載。

沒有跑這一點,但這裏是基本概念:

$sxe = simplexml_import_dom($this->xmlDocument); 

$data = $sxe->xpath('//entity[@id="700627"]'); 

    foreach ($data as $value) 
    { 
      $value->addChild('entity'); 
    }