Jump to content
php.lv forumi

Recommended Posts

Posted (edited)

Ir šāds kods, kur no xml [LV bankas xml faila] vajag masīvā dabūt vērtības.

<?php
$xmlstr = file_get_contents('xml.xml');
$xml = simplexml_load_string($xmlstr);
$currencyList = $xml -> body -> crates -> currencies -> currency;
foreach ($currencyList as $currencyItem){
	$currenty[$currencyItem -> id]["rate"] = $currencyItem -> rate;
	$currenty[$currencyItem -> id]["units"] = $currencyItem -> units;
}

echo  $currency["USD"]["units"]." USD = ".$currency["USD"]["rate"]."<br />";
echo  $currency["EUR"]["units"]." EUR= ".$currency["EUR"]["rate"]

?>

Edited by ray
Posted (edited)

Kas tieši nedarbojas ?

 

Failies neielasas, xml nenpārsējas ? $currencyList nav tas, ko tu domā ? Taču debugot vajag.

Edited by andrisp
Posted

kļūdas:

1. xml elementu nosaukumi ir case sensitive

2. $currency masīvs sākumā ir jāinitializē ar $currency = array();

3. $currencyList XML ceļš (path) nebija pareizs. Kad ielasi ar $xml = simplexml_load_* , tad tas $xml ir root elements, šajā gadījumā $xml elements ir CRates, un body nav vajadzīgs.

 

tagad darbojas:

<?php
$xmlstr = file_get_contents('xml.xml');
$xml = simplexml_load_string($xmlstr);
$currencyList = $xml ->Currencies->Currency;
$currency = array();
foreach ($currencyList as $currencyItem){
	$currency[(string)$currencyItem->ID]["rate"] = $currencyItem ->Rate;
	$currency[(string)$currencyItem->ID]["units"] = $currencyItem ->Units;
}

echo  $currency["USD"]["units"]." USD = ".$currency["USD"]["rate"]."<br />";
echo  $currency["EUR"]["units"]." EUR= ".$currency["EUR"]["rate"]

?>

Posted

kas nav kārtībā ar noapaļošanu, ka rāda rezultātā nulli?

	echo  $currency["USD"]["units"]." USD = ".round($currency["USD"]["rate"], 4)."<br />"; // 1 USD = 0
echo  $currency["EUR"]["units"]." EUR= ".round($currency["EUR"]["rate"], 4); // 1 EUR= 0

Posted (edited)

round() pirmajam parametram jābūt float tipa, bet tiek dots kā string, tāpēc ir jākonvertē. priekšā pieliec (float), piem round((float)$currency["USD"]

 

[edit] nē, dots tiek kā SimpleXML elements. labāk tur iekš cikla ["rate"] = $currencyItem->Rate pirms $currencyItem pieliec (string), tāpat pie Units rindiņas. Citādi masīvā tiek gāzti elementa objekti, bet tev vajag tikai string.

Edited by gurkjis
Posted (edited)

bez noapaļošanas:

 

1 USD = 0.47800000

1 EUR= 0.70280400

 

nesapratu par to string pielikšanu :/

Edited by ray
×
×
  • Create New...