无法编辑file_get_html字符串


String of file_get_html can't be edited?

考虑这段简单的代码,使用PHP Simple HTML DOM解析器正常工作,它输出当前社区

<?php
    //PHP Simple HTML DOM Parser from simplehtmldom.sourceforge.net
    include_once('simple_html_dom.php');
    //Target URL
    $url = 'http://stackoverflow.com/questions/ask';
    //Getting content of $url
    $doo = file_get_html($url);
    //Passing the variable $doo to $abd
    $abd = $doo ;
    //Trying to find the word "current community"
    echo $abd->find('a', 0)->innertext; //Output: current community. 
?>

考虑另一段代码,与上面相同,但我在解析的 html 内容中添加了一个空格(将来,我需要编辑此字符串,所以我只是在这里添加一个空格来简化事情)。

<?php
    //PHP Simple HTML DOM Parser from simplehtmldom.sourceforge.net
    include_once('simple_html_dom.php');
    //Target URL
    $url = 'http://stackoverflow.com/questions/ask';
    //Getting content of $url
    $doo = file_get_html($url);
    //Passing the variable $url to $doo - and adding an empty space.
    $abd = $doo . " ";
    //Trying to find the word "current community"
    echo $abd->find('a', 0)->innertext; //Outputs: nothing.     
?>

第二个代码给出此错误:

PHP Fatal error:  Call to undefined function file_get_html() in /home/name/public_html/code.php on line 5

为什么我无法编辑从file_get_html获取的字符串?出于许多重要原因,我需要对其进行编辑(例如在处理页面的 html 内容之前删除一些脚本)。我也不明白为什么它给出找不到 file_get_html() 的错误(很明显我们正在从第一个代码导入正确的解析器)。

附加说明:

我已经尝试了所有这些变化:

include_once('simple_html_dom.php');
require_once('simple_html_dom.php');
include('simple_html_dom.php');
require('simple_html_dom.php');

file_get_html()返回一个对象,而不是一个字符串。尝试将字符串连接到对象将调用对象的 _toString() 方法(如果存在),并且该操作将返回一个字符串。字符串没有 find() 方法。

如果要按照所描述的操作,请阅读文件内容并首先连接额外的字符串:

$content = file_get_contents('someFile.html');
$content .= "someString";
$domObject  = str_get_html($content);

或者,使用 file_get_html() 读取文件并使用 DOM API 对其进行操作。

$doo不是字符串!它是一个对象,一个简单HTML DOM的实例。不能对字符串调用->方法,只能对对象调用。不能将此对象视为字符串。试图将某些东西连接到它是没有意义的。 代码中的$abd是与字符串连接的对象的结果;这会导致字符串或错误,具体取决于对象的详细信息。它当然不会产生一个可用的对象,所以你当然不能$abd->find()

如果要修改页面的内容,请使用对象为您提供的 DOM API 进行操作。