2011-05-05 47 views
0

是的,我知道你可以使用JavaScript獲取體ID/jQuery來做到這一點,但我想用PHP(它更是一個學習的東西)。我無法安裝queryPath或phpQuery,因爲它位於客戶端的虛擬主機上。使用DOMXpath

基本上我修改

function getElementById($id) { 
    $xpath = new DOMXPath($this->domDocument); 
    return $xpath->query("//*[@id='$id']")->item(0); 
} 

使用,但

Fatal error: Using $this when not in object context in blahblahblah on line # 

拋出和$this是不確定的。

基本上我想要做的就是值相同頁面的主體ID的PHP上。

任何想法?

+3

queryPath和phpQuery不應該需要安裝 - 它們只是需要包含的PHP文件。對於你的問題更具針對性,你使用的是'$ this',它指的是當前對象,顯然你不使用面向對象的代碼。也許你可以爲你的代碼提供更廣泛的上下文,特別是設置了「domDocument」的地方。 – lonesomeday 2011-05-05 18:23:13

回答

0

它看起來像他正在試圖做一個函數來做一些xpath的東西更容易。

喜歡的東西

<?php 
function getElementById($id,$url){ 

$html = new DOMDocument(); 
$html->loadHtmlFile($url); //Pull the contents at a URL, or file name 

$xpath = new DOMXPath($html); // So we can use XPath... 

return($xpath->query("//*[@id='$id']")->item(0)); // Return the first item in element matching our id. 

} 

?> 

我沒有測試這一點,但它看起來是正確的。