Jump to content
php.lv forumi

masīva izveidošana no xml


ray

Recommended Posts

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
Link to comment
Share on other sites

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"]

?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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
Link to comment
Share on other sites

×
×
  • Create New...