-1

私はここに来ることをたくさん避けて私の問題を共有しました。私はたくさんグーグルして、いくつかの解決策を見つけましたが、確認されていません。まず、私の問題について説明します。

私のサイトには、ユーザーがコメントを投稿できるようにするためのCKEditorがあります。ユーザーが2つの投稿をクリックして複数引用すると、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を使用して文字列パターンを照合します。しかし、それが合法で効率的な解決策なのか、それとももっと良い解決策があるのか​​は確認されていません。より良い解決策があれば、私に提案してください。

4

3 に答える 3

3

DOMDocumentとを使用できますDOMXPath。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構文に慣れていない場合は、開始するためのいくつかの例を次に示します。

于 2013-03-24T18:36:40.857 に答える
1

HTML/XMLの処理に正規表現を使用しないでください。これがDOMDocumentSimpleXMLの目的です。

あなたの問題は比較的単純に見えるので、SimpleXMLを使用することで逃げることができるはずです(適切な名前ですよね?)

于 2013-03-24T18:20:50.027 に答える
0

正規表現でhtmlを解析しようとさえしないでください。単純なhtmldomをお勧めします。ここで入手:php html parser

于 2013-03-24T18:24:56.370 に答える