【问题标题】:Get the class tags using file_get_contents使用 file_get_contents 获取类标签
【发布时间】:2014-03-25 22:48:55
【问题描述】:

我正在编写我的 PHP 脚本来解析 html 网页。我使用file_get_contents打开url来获取内容列表。

代码如下:

$links = $row['links'];
$result = file_get_contents($links);
$html_content = str_replace("<a id='rowTitle1' class", "<a id='rowTitle1' class",$result);
print $html_content;

这是 html 输出:

<li class="zc-ssl-pg" id="row1-1" style="">
<span id="row1Time" class="zc-ssl-pg-time">6:00 PM</span>
<a id="rowTitle1" class="zc-ssl-pg-title" href='http://www.mysite.com'>The Middle</a>
<a class="zc-ssl-pg-ep" href='http://www.mysite.com'>"Thanksgiving IV"</a>

您能告诉我如何使用 file_get_contents 从 row1-1 类中的 row1Time、rowTitle1 和 zc-ssl-pg-ep 标签标签中获取值吗?

【问题讨论】:

  • 不确定您在那里用自身替换字符串的原因。 preg_match 在这种情况下是你的朋友。
  • 我倾向于将 HTML 加载到 DOMDocument 中并在那里进行任何操作。使用正则表达式解析 HTML 会变得非常棘手。
  • @halfer,没关系,只要 HTML 是相当静态的

标签: php html regex html-parsing


【解决方案1】:

正则表达式不是解析 HTML 的正确工具。 DOM 是完成这项工作的正确工具:

$dom = new DOMDocument();
$dom->loadHTML($result);
echo $dom->getElementById('row1Time')->nodeValue . "<br>";
echo $dom->getElementById('rowTitle1')->nodeValue . "<br>";
echo $dom->getElementsByTagName('a')->item(1)->nodeValue;

See it in action

由于 HTML 的结构,这仍然有点不确定,但如果它不改变,这将起作用。

【讨论】:

  • @John Conde 谢谢你,我在使用你的代码时遇到了问题。我有一个错误:解析错误:语法错误,意外'$dom'(T_VARIABLE)
  • 检查我上面的代码。可能缺少一个分号。
  • @JohnConde 我已经检查了你的代码并且我得到了它的工作,但页面显示为空。我在 html 源代码中只有“

    ”。我要输出的内容是下午 6:00,中间和“感恩节 IV”
  • 你发布的html是不是所有的html都要被解析?
  • 是的,这就是我真正想要解析的内容。
【解决方案2】:
$links = $row['links'];
$result = file_get_contents($links);
// $html_content = str_replace("<a id='rowTitle1' class", "<a id='rowTitle1' class",$result); // thats useless !

preg_match('/<span id="row1Time" class="zc-ssl-pg-time">([^<]+)<\/span>/', $html_content, $matches);
$row1Time = $matches[1];

preg_match('/<a id="rowTitle1" class="zc-ssl-pg-title" href='http:\/\/www\.mysite\.com'>([^<]+)<\/a>/', $html_content, $matches);
$rowTitle1 = $matches[1];

print $html_content;

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多