gpt4 book ai didi

PHP DOMDocument 解析 HTML

转载 作者:行者123 更新时间:2023-12-03 15:59:40 26 4
gpt4 key购买 nike

我有以下 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);

获取<img src="">相对于 div 节点的属性节点。如果您遵循我的建议,您的示例应该没问题。


这是遵循上述内容的代码版本:

$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;
}
}

关于PHP DOMDocument 解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15023805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com