2015-12-23 89 views
1

取特定的nodeValue我有這個multipel Xpath查詢從多Xpath查詢

$data = $xpath->query("//li/span[contains(@class, 'cmil_salong')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_time')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_versions')]/div[contains(@class, 'mv_3d')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_versions')]/div[contains(@class, 'mv_txt')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_rs')] | 
//li[contains(@class, 'selectShowRow')]/div[contains(@class, 'cmil_btn')]/a[contains(@class, 'smallYellowBtn smallBtn')]/@href"); 

即取六(6)nodeValues。

我試過$node->nodeValue->item(0),但那給了我Fatal error: Call to a member function item() on string in

問題:是否有可能在foreach循環中更具體,我想要回顯哪個nodeValue? (對不起,僞代碼,只是爲了我的問題的說明):

foreach ($this->xpathquery as $node) { 
    echo 'This is query reuslt of query 0: ' .$node->nodeValue->item(0) .'<br>'>; 
    echo 'This is query reuslt of query 1: ' .$node->nodeValue->item(1) .'<br>'>; 
    echo 'This is query reuslt of query 2: ' .$node->nodeValue->item(2) .'<br>'>; 
    echo 'This is query reuslt of query 3: ' .$node->nodeValue->item(3) .'<br>'>; 
    echo 'This is query reuslt of query 4: ' .$node->nodeValue->item(4) .'<br>'>; 
    echo 'This is query reuslt of query 5: ' .$node->nodeValue->item(5) .'<br>'>; 
} 

(我想我在PHP 5.6.10運行的XPath V1)

回答

1

我認爲在你的foreach變量$node是類型DOMElementDOMAttr,那些沒有方法item

但是,因爲你得到6個nodeValues,也許你可以在你的foreach結構添加使用 '$鍵':

foreach ($this->xpathquery as $key => $node) {

然後,您可以檢查$key這樣的:

foreach ($this->xpathquery as $key => $node) { 
    if ($key === 0) { 
     echo $node->nodeValue; 
    } 
} 

根據你的評論,也許另一種選擇可能是檢查的$node

這可以是'DOMElement'或'DOMAttr'。

然後做一次檢查的類屬性或節點名稱:

foreach ($this->xpathquery as $key => $node) { 
    if ($node->nodeType === 1) { 
     if ($node->hasAttribute('class')) { 
      switch ($node->getAttribute('class')) { 
       case "cmil_salong": 
        echo $node->nodeValue; 
        break; 
       case "mv_3d": 
        echo $node->nodeValue; 
        break; 
       // etc .. 
      } 
     } 
    } 
    if ($node->nodeType === 2) { 
     if ($node->nodeName === 'href') { 
      echo $node->nodeValue; 
     } 
    } 
} 
+0

謝謝您的回答!我已經嘗試過,事情是空值不返回。所以循環可能會因此而搞砸。 – Adam

+0

@亞當我已經添加了另一個選項,我的答案可能會幫助你。 –

+0

哇!令人敬畏的工作!非常感謝您的時間和解決問題的非常好的方法! – Adam