עיבוד XML שערי מטבעות של בנק ישראל
במדריך זה סקריפט קצר שמגרד קובץ XML של שערי מטבעות מבנק ישראל.
פתיחת ה-URL המרוחק נעשית באמצעות cURL העדיפה כשרוצים לגרד תוכן של דפים מרשת האינטרנט (מדריך cURL ב-PHP).
הדף של בנק ישראל מקודד בפורמט-XML, ולכן מיצוי המידע נעשה באמצעות simplexml_load_string.
הטיפול בשגיאות נעשה בעזרת בלוק try...catch (מדריך טיפול ב-exception).
function get_dollar_rate_from_remote_url()
{
$url = 'https://www.boi.org.il/currency.xml?curr=01';
try{
$feed = file_get_contents_curl($url);
$currencyFeed = simplexml_load_string($feed);
if(!$currencyFeed || !isset($currencyFeed->CURRENCY)):
throw new UnexpectedValueException("No feed from : $url");
else:
$currencies = $currencyFeed->CURRENCY;
$c = xml2array ($currencies);
if(isset($c['NAME']) && isset($c['COUNTRY']) && isset($c['RATE']) && $c['NAME'] === 'Dollar' && $c['COUNTRY'] === 'USA'):
$rate = $c['RATE'];
// update table
// send email
endif;
endif;
} catch (Exception $e){
exit($e -> getMessage());
}
}
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
אהבתם? לא אהבתם? דרגו!
0 הצבעות, ממוצע 0 מתוך 5 כוכבים