Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Código para obtener el precio del dolar desde la bolsa electrónica de santiago. Era para un mini-proyecto, no lo critiquen tanto
<?php
/**
* Código para obtener el precio del dolar desde la bolsa electrónica de santiago
*/
class BolsaElectronicaDolarAPI
{
private $dominio = "http://www.bolchile.cl";
private $url = "/portlets/Dolar2Portlet/XmlApiGraf?idioma=es&intervalo=60&periodo=HOY&mayorA10=true";
private $ultimos_cuanto = 30;
function __construct()
{
}
function ObtenerPrecioDolar()
{
$datos_cvs = $this->ObtenerDatos();
$arrResult = [];
while (($data = fgetcsv($datos_cvs, 1000, ";")) !== FALSE) {
$arrResult[] = $data;
}
return array(
"ultimo" => (float)(str_replace(',','.',end($arrResult)[1])),
"promedio_ultimos" => $this->PromedioDolar($arrResult)
);
}
private function PromedioDolar($array)
{
$promedio = 0;
$cantidad = min(count($array),$this->ultimos_cuanto);
foreach(array_slice($array, -1*$cantidad) as $elemento)
{
$promedio += (float)(str_replace(',','.',$elemento[1]));
}
return $promedio/$cantidad;
}
private function ObtenerDatos()
{
return fopen($this->dominio . $this->url, "r");
}
}
header("Content-Type:text/plain");
$api = new BolsaElectronicaDolarAPI();
print_r($api->ObtenerPrecioDolar());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment