使用DOMXpath获取正文ID

时间:2011-05-05 18:18:04

标签: php dom xpath this domxpath

是的,我意识到你可以使用javascript / jQuery来做到这一点,但我想使用PHP(它更像是一种学习的东西)。我无法安装queryPath或phpQuery,因为这是在客户端的webhost上。

基本上我正在修改

    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未定义。

基本上我要做的就是获取PHP所在页面的body id值。

有什么想法吗?

1 个答案:

答案 0 :(得分: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.

}

?>

我没有对此进行测试,但看起来是对的。

相关问题