Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 获取元素外部的文本_Php_Simple Html Dom - Fatal编程技术网

Php 获取元素外部的文本

Php 获取元素外部的文本,php,simple-html-dom,Php,Simple Html Dom,我正在使用简单的HTMLDOM来抓取一个网站。我遇到的问题是,文本位于任何特定元素之外。它似乎唯一在里面的元素是 我还是个新手,还在学习。有人能帮忙吗?你就快到了。。。使用测试循环显示节点的内容,并找到所需文本的索引。例如: // Find all texts $texts = $html->find('div#content text'); foreach ($texts as $key => $txt) { // Display text and the parent'

我正在使用简单的HTMLDOM来抓取一个网站。我遇到的问题是,文本位于任何特定元素之外。它似乎唯一在里面的元素是


我还是个新手,还在学习。有人能帮忙吗?

你就快到了。。。使用测试循环显示节点的内容,并找到所需文本的索引。例如:

// Find all texts
$texts = $html->find('div#content text');

foreach ($texts as $key => $txt) {
    // Display text and the parent's tag name
    echo "<br/>TEXT $key is ", $txt->plaintext, " -- in TAG ", $txt->parent()->tag ;
}
如果你的文本并不总是有相同的索引,但你知道它跟在
h3
标题后面,那么你可以使用如下内容:

foreach ($texts as $key => $txt) {
    // Locate the h3 heading
    if ($txt->parent()->tag == 'h3') {
        // Grab the next index content from $texts
        echo $texts[$key+1]->plaintext;
        // Stop
        break;
    }
}

谢谢你,Enissay,一旦我知道你的代码在做什么,一切都是有意义的。这是一个很好的解决问题的方法。非常感谢。实际上,这在我一直测试的列表页面上非常有效,但是网站上的每个列表页面都有我想要分配给不同“文本编号”的文本。每页都不一样。有什么办法可以绕过这个问题吗?谢谢Enissay,我刚刚又尝试了一次,并成功地显示了一些文本,但是只显示了第一句话(重复了大约50次)。我需要的文本段落中的每个句子都用
标记隔开,[$key+1]代码只返回第一个句子,[$key+3]代码只返回第二个句子,等等。。。有什么想法吗?嗯,一个快速的想法是删除所有的
br
foreach($scrap->find(“br”)as$br){$br->outertext=“”;}
。然后应用你的代码。。。希望这有帮助…非常感谢你的帮助。不幸的是,我无法让它工作,因为它似乎与页面上的其余代码冲突。我将尝试再次访问它很快,希望能找到一个解决方案。再次感谢。
// Find all texts
$texts = $html->find('div#content text');

foreach ($texts as $key => $txt) {
    // Display text and the parent's tag name
    echo "<br/>TEXT $key is ", $txt->plaintext, " -- in TAG ", $txt->parent()->tag ;
}
$scrape->find("div#content text",4);
foreach ($texts as $key => $txt) {
    // Locate the h3 heading
    if ($txt->parent()->tag == 'h3') {
        // Grab the next index content from $texts
        echo $texts[$key+1]->plaintext;
        // Stop
        break;
    }
}