使用 PHP 的 HTML DOMDocument 解析 HTML
可以使用以下程式碼獲取 class="text" 中的 <div> 標籤中的文字,其處於有 class="main" 的 <div> 標籤中 −
示例
$html = <<<HTML
<div class="main">
<div class="text">
This is text 1
</div>
</div>
<div class="main">
<div class="text">
This is text 2
</div>
</div>
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
XPath queries along with the DOMXPath::query method can be used to return the list of elements that are searched for by the user.
$tags = $xpath->query('//div[@class="main"]/div[@class="text"]');
foreach ($tags as $tag) {
var_dump(trim($tag->nodeValue));
}輸出
將生成以下輸出 −
string ‘This is text 1’ (length=14) string ‘This is text 2' (length=14)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP