PHP脚本,用于读取外部HTML源代码并列出标记之间的代码

时间:2010-07-08 22:32:25

标签: php html-parsing

基本上我想写一些PHP代码,列出来自外部网址的<h1>标签之间的所有内容。

我不想只是第一个而是全部。所以,如果外部网站的来源是

<html>
  <title></title>
  <head></head>
  <h1>Test Here</h1>
  <h1>Test here</h1>
</html>

我想创建一个只生成<h1>标记之间内容的脚本:

Test Here
Test here

我熟悉PHP,但我不能想到那样做的脚本。

1 个答案:

答案 0 :(得分:4)

simple_html_dom是你的朋友。

$dom = file_get_html("http://yourserver.com/path/to/file.html");
// alternatively use str_get_html($html) if you have the html string already...

foreach ($dom->find("h1") as $node)
{
    echo $node->innertext;
}

它非常强大,可以做很多事情。