Programming Learning Diary

네이버 환율 파싱

페이지 정보

작성일 21-02-12 14:22

본문

function Ncurrency($items) {
$Data = array();
# 데이터 호출
$url = 'https://finance.naver.com/marketindex/exchangeList.nhn';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
if(!$response) return $Data;
$res = iconv('euc-kr', 'UTF-8', $response);
# 파싱
preg_match('#<tbody.*?>.*?</tbody>#s', $res, $tbody); if(!$tbody) return $Data;
preg_match_all('#<tr.*?>(.*?)</tr>#s', $tbody[0], $tr); if(!$tr) return $Data;
foreach($tr[1] as $v) {
preg_match_all('#<td.*?>(.*?)</td>#s', $v, $td);
$td = $td[1];
$td[0] = preg_replace('#^\s+|\s+$#s', '', strip_tags($td[0]));
$akey = preg_replace('#[^A-Z]+#s', '', $td[0]); if(!$akey) return $Data;
for ($i=0; $i<count($items); $i++)
$Data[$akey][$items[$i]] = $td[$i];
}
return $Data;
}
$items = array('통화명', '매매기준율', '현찰살때', '현찰팔때', '송금보낼때', '송금받을때', '미화환산율');
$Data = Ncurrency($items);
$html = '<table border=1><tr>';
foreach ($items as $v)
$html .= "<th>$v</th>";
$html .= '</tr>';
foreach ($Data as $k => $v) {
$html .= '<tr>';
foreach ($items as $v1)
$html .= "<td>{$Data[$k][$v1]}</td>";
$html .= '</tr>';
}
echo $html . '</table>';

댓글목록

등록된 댓글이 없습니다.