从 SimpleXMLElement 对象获取 php 数组的值

Get values from SimpleXMLElement Object for php array

我需要帮助解决这个问题,似乎我无法从 SimpleXMLElement Object

中得到 targetCurrency
$xmlString = <<<XML
<channel>
    <title>XML ~~ Exchange Rates ~~</title>
    <language>en</language>
    <item>
        <baseCurrency>USD</baseCurrency>
        <targetCurrency>EUR</targetCurrency>
        <targetName>Euro</targetName>
        <exchangeRate>0.90900497</exchangeRate>
    </item>
</channel>
XML;

$xml = simplexml_load_string($xmlString);
        
foreach($xml->item as $rate){
    
    $rate       = (string) $rate->exchangeRate;
    $curr_code  = (string) $rate->targetCurrency;
     
    $money[] = array('rate' => $rate, 'curr_code' =>  $curr_code);
}
        
print_r($money);

这输出:

Array
(
    [0] => Array
        (
            [rate] => 0.90947603
            [curr_code] => 
        )
)

[curr_code] 应该输出 'EUR'.

我该如何解决?

改用 xpath 试试:

$items  = $xml->xpath("//item");
foreach($items as $item){
    $rate = $item->xpath('.//exchangeRate')[0];
    $curr_code  = $item->xpath('.//targetCurrency')[0]; 
    $money[] = array('rate' => $rate, 'curr_code' =>  $curr_code);
 }
    
print_r($money);

输出应该符合预期。

您对两个不同的事物使用相同的变量名:

foreach($xml->item as $rate){
    // at this point, $rate is the <item> element

    $rate       = (string) $rate->exchangeRate;
    // now $rate is a string with the exchange rate

    $curr_code  = (string) $rate->targetCurrency;
    // so now this won't work

    $money[] = array('rate' => $rate, 'curr_code' =>  $curr_code);
}

如果您 运行 display_errors 打开或检查您的日志,您会看到这样的消息:

Notice: Trying to get property 'targetCurrency' of non-object

或者在PHP8中,这个:

Warning: Attempt to read property "targetCurrency" on string


解决方法是更仔细地命名您的变量:

foreach($xml->item as $itemElement){
    $rate = (string) $itemElement->exchangeRate;
    $curr_code  = (string) $itemElement->targetCurrency;
    $money[] = array('rate' => $rate, 'curr_code' =>  $curr_code);
}