-2

重複の可能性:
PHPでHTMLを解析および処理する方法は?

このコードを使用して、特定のURLのWebサイトからHTMLコンテンツを取得しました。

**Code:**

=================================================================

example URL: http://www.qatarsale.com/EnMain.aspx

/*

$regexp = '/<div id="UpdatePanel4">(.*?)<\/div>/i';

@preg_match_all($regexp, @file_get_contents('http://www.qatarsale.com/EnMain.aspx'), $matches, PREG_SET_ORDER);*/

/*

ただし、$matchesは空白の配列を返します。div id="UpdatePanel4"にあるすべてのhtmlコンテンツをフェッチしたい。

誰かが解決策を持っているなら、私に提案してください。

ありがとう

4

3 に答える 3

3

まず、サーバーがデータを取得できることを確認します。

次に、代わりに html パーサーを使用してデータを解析します。

$html = @file_get_contents('http://www.qatarsale.com/EnMain.aspx');
if (!$html) {
  die('can not get the content!');
}
$doc = new DOMDocument();
$doc->loadHTML($html);
$content = $doc->getElementById('UpdatePanel4');
于 2012-06-28T07:38:09.983 に答える
0
// Gets the webpage
$html = @file_get_contents('http://www.qatarsale.com/EnMain.aspx');

$startingTag = '<div id="UpdatePanel4">';
// Finds the position of the '<div id="UpdatePanel4">
$startPos = strpos($html, $startingTag);
// Get the position of the closing div
$endPos = strpos($html, '</div>', $startPos + strlen($startingTag));
// Get the content between the start and end positions
$contents = substr($html, $startPos + strlen($startingTag), $endPos);

その UpdatePanel4 div にさらに div が含まれている場合は、もう少し作業を行う必要があります。

于 2012-06-28T07:35:34.197 に答える
0

それは役に立ちません。正規表現を機能させることができたとしても、それを使用する方法には 2 つの問題があります。

  • サーバーが次のように HTML のマイナーなものを変更するとどうなります<div data-blah="blah" id="UpdatePanel4">か? その場合、正規表現も変更する必要があります。

  • innerHTML2 番目の問題: divが必要だと思いますよね? その場合、正規表現を使用して対処する方法は、ネストやツリー構造に注意を払っていません。取得する文字列は、指定したものから最初 </div>に検出されたものまでです。

解決:

正規表現を使用して HTML を解析することは、常に悪い考えです。代わりにDOMDocumentを使用してください。

于 2012-06-28T07:38:34.773 に答える