繁体   English   中英

使用PHP从HTML字符串获取特定数据的快速方法

[英]Fast way to get specific data from HTML string using PHP

我避免很多来这里分享我的问题。 我在Google上搜索了很多,找到了一些解决方案,但未得到证实。 首先,我解释我的问题。

我的网站上有一个CKEditor,可让用户发表评论。 假设用户单击两个帖子以多引用它们,则数据将在CKEditor中是这样的

<div class="quote" user_name="david_sa" post_id="223423">
This is Quoted Text 
</div>

<div class="quote" user_name="richard12" post_id="254555">
This is Quoted Text 
</div>

<div class="original">
This is the Comment Text 
</div>

我想在php中分别获取所有元素,如下所示

user_name = david_sa
post_id = 223423;
quote_text = This is Quoted Text

user_name = david_sa
post_id = richard12;
quote_text = This is Quoted Text

original_comment = This is the Comment Text 

我想以PHP的上述格式获取数据。 我已经在Google上搜索,发现我的问题附近有preg_match_all()PHP函数,该函数使用REGEX来匹配字符串模式。 但是我不确定这是否是合法有效的解决方案,还是有更好的解决方案。 如果您有更好的解决方案,请建议我。

您可以为此使用DOMDocumentDOMXPath 只需很少的代码行即可解析HTML并从中提取几乎所有内容。

$doc = new DOMDocument();
$doc->loadHTML(
'<html><body>' . '

<div class="quote" user_name="david_sa" post_id="223423">
This is Quoted Text 
</div>

<div class="quote" user_name="richard12" post_id="254555">
This is Quoted Text 
</div>

<div class="original">
This is the Comment Text 
</div>

' . '</body></html>');

$xpath = new DOMXPath($doc);

$quote = $xpath->query("//div[@class='quote']");
echo $quote->length; // 2
echo $quote->item(0)->getAttribute('user_name'); // david_sa
echo $quote->item(1)->getAttribute('post_id');   // 254555

// foreach($quote as $div) works as expected

$original = $xpath->query("//div[@class='original']");
echo $original->length;             // 1
echo $original->item(0)->nodeValue; // This is the Comment Text

如果您不熟悉XPath语法,那么请参考以下示例

您不应该使用正则表达式来处理HTML / XML。 这就是DOMDocumentSimpleXML的基础。

您的问题似乎相对简单,因此您应该能够使用SimpleXML(恰当地命名,对吧?)

甚至不要尝试使用正则表达式来解析html。 我会推荐简单的HTML dom。 在这里获取: php html解析器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM