2013-03-24 32 views
-1

我避免了很多來這裏分享我的問題。我搜索了很多,並找到一些解決方案,但沒有得到證實。 首先我解釋我的問題。使用PHP從HTML字符串獲取特定數據的快速方法

我的網站上有一個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中。我搜索了一下,發現preg_match_all()PHP函數接近我的問題,它使用REGEX來匹配字符串模式。但我沒有證實這是一個合法和有效的解決方案,或者有更好的解決方案。如果您有更好的解決方案,請推薦我。

+2

奇怪,連續兩個問題詢問如何用正則表達式解析html。正確的方法是使用simplexml或DOM來解析(x)html並獲取attrs和節點值 – Alexey 2013-03-24 18:14:08

+0

@Alexey - 我正在閱讀「PHP面向對象的解決方案」來強化我的oop並閱讀關於simpleXML的章節,但我認爲爲什麼我應該讀它,並跳過它,突然我來到這裏。現在我明白了simpleXML的價值並閱讀了這個章節。謝謝。對於無關的評論感到抱歉。 – netsmertia 2013-03-24 19:10:50

+0

n/p - 請參閱有人使用DOM擴展爲您提供了以下工作代碼。 – Alexey 2013-03-24 19:14:56

回答

2

對此,您可以使用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 syntax然後here are a few examples讓你開始。

+0

+1任何人都可以提供鏈接。你的建議,例子,以及更多的例子/展開的鏈接,這是一個非常好的答案。 – Josh 2013-03-24 18:44:02

+0

@Salman謝謝你提供代碼示例,你節省了我很多的時間。 – 2013-03-25 03:23:31

1

你不應該使用正則表達式來處理HTML/XML。這就是DOMDocumentSimpleXML的內置。

您的問題似乎比較簡單,所以你應該能夠逃脫使用SimpleXML(適當命名的,是吧?)

0

甚至不要嘗試正則表達式來解析HTML。我會推薦簡單的HTML DOM。在此處獲取:php html parser

相關問題