よし、これをやろう。最初にデータをHTMLパーサーにロードし、次にそれからXPathパーサーを作成します。XPathは、HTMLを簡単にナビゲートするのに役立ちます。それで:
$date = "20110509";
$data = file_get_contents("http://online.wsj.com/mdc/public/page/2_3021-tradingdiary2-{$date}.html?mod=mdc_pastcalendar");
$doc = new DOMDocument();
@$doc->loadHTML($data);
$xpath = new DOMXpath($doc);
次に、いくつかのデータを取得する必要があります。まず、すべてのデータテーブルを取得しましょう。ソースを見ると、これらのテーブルは次のクラスで示されていますmdcTable
。
$result = $xpath->query("//table[@class='mdcTable']");
echo "Tables found: {$result->length}\n";
ここのところ:
$ php test.php
Tables found: 5
さて、テーブルがあります。次に、特定の列を取得する必要があります。それでは、あなたが言及した最新のクローズ列を使用しましょう:
$result = $xpath->query("//table[@class='mdcTable']/*/td[contains(.,'Latest close')]");
foreach($result as $td) {
echo "Column contains: {$td->nodeValue}\n";
}
これまでの結果:
$ php test.php
Column contains: Latest close
Column contains: Latest close
Column contains: Latest close
... etc ...
次に、特定の行の特定の列を取得するための列インデックスが必要です。これを行うには、前の兄弟要素をすべてカウントしてから、1つ追加します。これは、要素インデックスセレクターが0インデックスではなく、1インデックスであるためです。
$result = $xpath->query("//table[@class='mdcTable']/*/td[contains(.,'Latest close')]");
$column_position = count($xpath->query('preceding::*', $result->item(0))) + 1;
echo "Position is: $column_position\n";
結果は次のとおりです。
$ php test.php
Position is: 2
次に、特定の行を取得する必要があります。
$data_row = $xpath->query("//table[@class='mdcTable']/*/td[starts-with(.,'Closing Arms')]");
echo "Returned {$data_row->length} row(s)\n";
ここではstarts-with
、行ラベルにutf-8記号が含まれているため、を使用します。これにより、簡単になります。これまでの結果:
$ php test.php
Returned 4 row(s)
次に、列インデックスを使用して、必要なデータを取得する必要があります。
$data_row = $xpath->query("//table[@class='mdcTable']/*/td[starts-with(.,'Closing Arms')]/../*[$column_position]");
foreach($data_row as $row) {
echo "{$date},{$row->nodeValue}\n";
}
結果は次のとおりです。
$ php test.php
20110509,1.26
20110509,1.40
20110509,0.32
20110509,1.01
これでファイルに書き込むことができます。さて、これらが適用される市場がないので、先に進んでそれらをつかみましょう:
$headings = array();
$market_headings = $xpath->query("//table[@class='mdcTable']/*/td[@class='colhead'][1]");
foreach($market_headings as $market_heading) {
$headings[] = $market_heading->nodeValue;
}
これで、カウンターを使用して、現在の市場を参照できます。
$data_row = $xpath->query("//table[@class='mdcTable']/*/td[starts-with(.,'Closing Arms')]/../*[$column_position]");
$i = 0;
foreach($data_row as $row) {
echo "{$date},{$headings[$i]},{$row->nodeValue}\n";
$i++;
}
出力は次のとおりです。
$ php test.php
20110509,NYSE,1.26
20110509,Nasdaq,1.40
20110509,NYSE Amex,0.32
20110509,NYSE Arca,1.01
今あなたの部分のために:
- これは、日付を取る関数にすることができます
- ファイルを書き出すためのコードが必要になります。ヒントについては、ファイルシステム関数を確認してください
- これは、さまざまな列とさまざまな行を使用するように拡張可能にすることができます