使用 DOMXpath 获取正文 ID


Get body id using DOMXpath

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

基本上我正在修改

    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所在页面的正文ID值。

有什么想法吗?

看起来他只是想让一个函数更容易地做一些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.
}
?>

我没有测试这个,但它看起来是正确的。