Парсинг биржевых котировок

Решение задачи по парсингу биржевых котировок с финансовых сайтов. Используется только CURL для получения информации, все остальное — чистый PHP.

function get_web_page($url) {

$uagent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1017.2 Safari/535.19";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // возвращает веб-страницу
curl_setopt($ch, CURLOPT_HEADER, false); // не возвращает заголовки
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // переходит по редиректам
curl_setopt($ch, CURLOPT_ENCODING, ""); // обрабатывает все кодировки
curl_setopt($ch, CURLOPT_USERAGENT, $uagent); // useragent
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // таймаут соединения
curl_setopt($ch, CURLOPT_TIMEOUT, 120); // таймаут ответа
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // останавливаться после 10-ого редиректа

$content = curl_exec($ch);

curl_close($ch);

return $content;
}

$url = "http://www.finam.ru";

$result = get_web_page($url);

//print $result;
//$text = $result;

print "
";
print "";

$result= mb_convert_encoding($result,'UTF-8','Windows-1251');

//VTB AO
$findme = $result;
$findme0 = "ВТБ ао";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,5); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

//BRENT
$findme = $result;
$findme0 = "Brent*";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,6); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

//NICKEL
$findme = $result;
$findme0 = "Никель";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,5); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

//GOLD
$findme = $result;
$findme0 = "Золото";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,7); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

print "";

?>

 

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

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

Как то надо было доставать котировки валют с внешнего сайта. Использовал 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