[英]PHP DOMDocument parse HTML
我有以下 HTML 標記
<div contenteditable="true" class="text"></div>
<div contenteditable="true" class="text"></div>
<div style="display: block;" class="ui-draggable">
<img class='avatar' src=""/>
<p style="">
<img class='pic' src=""/><br>
<span class='fulltext' style="display:none"></span>
</p>-<span class='create'></span>
<a class='permalink' href=""></a>
</div>
<div contenteditable="true" class="text"></div>
<div style="display: block;" class="ui-draggable">
<img class='avatar' src=""/>
<p style="">
<img class='pic' src=""/><br>
<span class='fulltext' style="display:none"></span>
</p><span class='create'></span><a class='permalink' href=""></a>
</div>
父 div 可以更多。為了解析信息並將其插入到數據庫中,我使用以下代碼 -
$dom = new DOMDocument();
$dom->loadHTML($xml);
$xpath = new DOMXPath($dom);
$div = $xpath->query('//div');
$i=0;
$q=1;
foreach($div as $book) {
$attr = $book->getAttribute('class');
//if div contenteditable
if($attr == 'text') {
echo '</br>'.$book->nodeValue."</br>";
}
else {
$new = new DOMDocument();
$newxpath = new DOMXPath($new);
$avatar = $xpath->query("(//img[@class='avatar']/@src)[$q]");
$picture = $xpath->query("(//p/img[@class='pic']/@src)[$q]");
$fulltext = $xpath->query("(//p/span[@class='fulltext'])[$q]");
$permalink = $xpath->query("(//a[@class='permalink'])[$q]");
echo $permalink->item(0)->nodeValue; //date
echo $permalink->item(0)->getAttribute('href');
echo $fulltext->item(0)->nodeValue;
echo $avatar->item(0)->value;
echo $picture->item(0)->value;
$q++;
}
$i++;
}
但我認為解析 HTML 有更好的方法。 有沒有? 先感謝您
請注意, DOMXPath::query
支持名為contextparam
的第二個參數。 此外,您將不需要循環內的第二個 DOMDocument 和 DOMXPath。 采用:
$avatar = $xpath->query("img[@class='avatar']/@src", $book);
獲取相對於 div 節點的<img src="">
屬性節點。 如果你遵循我的建議,你的例子應該沒問題。
這是您的代碼的一個版本,它遵循上述內容:
$dom = new DOMDocument();
$dom->loadHTML($xml);
$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div');
foreach($divs as $book) {
$attr = $book->getAttribute('class');
if($attr == 'text') {
echo '</br>'.$book->nodeValue."</br>";
} else {
$avatar = $xpath->query("img[@class='avatar']/@src", $book);
$picture = $xpath->query("p/img[@class='pic']/@src", $book);
$fulltext = $xpath->query("p/span[@class='fulltext']", $book);
$permalink = $xpath->query("a[@class='permalink']", $book);
echo $permalink->item(0)->nodeValue; //date
echo $permalink->item(0)->getAttribute('href');
echo $fulltext->item(0)->nodeValue;
echo $avatar->item(0)->value;
echo $picture->item(0)->value;
}
}
事實上,您的做法是正確的:必須使用 DOM 對象解析 html。 然后可以進行一些優化:
$div = $xpath->query('//div');
非常貪婪, getElementsByTagName 應該更合適:
$div = $dom->getElementsByTagName('div');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.