试图做一些网页抓取,但无法理解PHP如何解析html标签。我目前不在我的网络服务器上,所以我在线测试代码。 在http://phptester.net/我的代码是这样的:PHP和html标签
<?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是什么。它只是text.but,因为你已经注释掉了'scrape_str',你实际上是在对'substr()'的结果进行'=== false'测试,它只会在失败时返回false。 –
如果php将html视为文本,那么为什么它会将