試圖做一些網頁抓取,但無法理解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視爲文本,那麼爲什麼它會將