【发布时间】:2016-08-24 15:20:26
【问题描述】:
尝试做一些网页抓取,但无法理解 php 如何解析 html 标签。我目前不在我的网络服务器上,所以我正在在线测试代码。 在http://phptester.net/ 我的代码是这样的:
<?php
$start = "<title>";
$end = "</title>";
$data = "<title>this is a test </title>";
echo $start . " " . $end . " " . "<br>";
echo $data . "<br>";
echo strlen($start) . "<br>";
echo htmlspecialchars($data) . "<br>";
$data = stristr(htmlspecialchars($data), htmlspecialchars($start));
$data = substr(htmlspecialchars($data), strlen($start));
if($data===false){
echo 'string not found';
}
else{
echo $data;
}
现在是一些示例输入和输出。
Input
$start="<title>"
$end="</title>"
Output
(blank line)
(blank line)
7
<title>this is a test </title>
;title>this is a test </title>
Input
$start=<title>
$end=</title>
Output
<title> </title>
(blank line)
13
<title>this is a test </title>
string not found
变化
$data = stristr(htmlspecialchars($data), htmlspecialchars($start));
到
$data = stristr(htmlspecialchars($data), $start);
并重新测试。
Input
$start="<title>"
$end="</title>"
Output
(blank line)
(blank line)
7
<title>this is a test </title>
string not found
Input
$start="<title>"
$end="</title>"
Output
<title> </title>
(blank line)
13
<title>this is a test </title>
>this is a test </title>
我期待最后一个工作。我认为它将在实际的 Web 服务器上,因为似乎这个在线 php 测试器在字符串的开头插入了额外的 4 个字符,以防止最后四个字符被删除。
接下来我尝试了http://sandbox.onlinephpfunctions.com/,没有任何 htmlspecialchar 函数的原始字符串完全符合我的预期。我在他们两个中都使用了相同的版本。现在我很困惑。
抱歉,帖子太长了。如果有人可以向我解释 php 如何解析 html 标签,我将不胜感激。谢谢。
【问题讨论】:
-
PHP 不会随机解析 HTML。要实际解析您想要的 HTML,例如DomDocument 或 SimpleXML 扩展。正如你所说,你的帖子很长,所以我很难真正弄清楚你想要表达什么。
-
php 不知道 html 是什么。这只是文本。但是由于您已经注释掉了您的
scrape_str,因此您实际上是在针对substr()的结果进行=== false测试,这只会在失败时返回false。 -
如果 php 将 html 视为文本,那么为什么将
视为特殊字符?为什么它不只是将其视为常规字符串? -
是的,这很不错——我过去用过。 simplehtmldom.sourceforge.net
-
@RichardHousham OH GOODNESS SOURCEFORGE :melty_face_emoji:
标签: php html string-parsing