Парсинг котировок валют

Written by

in

Как то надо было доставать котировки валют с внешнего сайта. Использовал CURL для получения контента и простой xml_parser_create для парсинга информации.

$res = \'\';

function startElement($parser, $name, $attrs) {
global $res;
switch ($name) {
case \'VALCURS\':
$d = mb_convert_encoding(urldecode($attrs[\'DATE\']),\'UTF-8\', \'windows-1251\');
//$dd = $d[0].$d[1].$d[2].$d[3].$d[4];
//$res .= \'Дата: \'.$dd.\'\';
break;
}
}

function endElement($parser, $name) {}

function contents($parser, $data) {
global $res;
$data = mb_convert_encoding($data,\'windows-1251\',\'UTF-8\');
//$res .= trim($data).\"\";
}

$ch = curl_init();

//$date = date(\"d/m/Y\");
//$url = \"http://www.cbr.ru/scripts/XML_daily.asp?///date_req=\".$date;
$url = \"http://www.cbr.ru/scripts/XML_daily.asp\";

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_PROXYPORT, 0);
curl_setopt($ch, CURLOPT_PROXY, \'\');

$data = curl_exec($ch);

curl_close($ch);

$XMLparser = xml_parser_create();

xml_set_element_handler($XMLparser, \'startElement\', \'endElement\');
xml_set_character_data_handler($XMLparser, \'contents\');

$xml_array = file($url);

$res .= \"\".$xml_array[67].\": \".$xml_array[70].\"\";
$res .= \"\".$xml_array[74].\": \".$xml_array[77].\"\";
print $res;

if (!xml_parse($XMLparser, $data)) {
die(\'Ошибка обработки данных\');
}

xml_parser_free($XMLparser);
?>

Интересная инфа тут: http://parsing-and-i.blogspot.com

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *