Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I avoided a lot to come here share my problem. I have googled a lot and find some solutions but not confirmed. First I explain My Problem.

I have a CKEditor in my site to let the users post comments. Suppose a user clicks two posts to Multi quote them, the data will be like this in 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>

I want to get all the elements separately in php as below

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 

I want to get the data in above format in PHP. I have googled and found the preg_match_all() PHP function near to my problem, that uses the REGEX to match the string patterns. But I am not confirmed that is it a legitimate and efficient solution or there is some better solution. If You have any better solution Please Suggest Me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use DOMDocument and DOMXPath for this. It takes very few lines of code to parse HTML and extract just about anything from it.

$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

If you are not familiar with XPath syntax then here are a few examples to get you started.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...