如何在 PHP 中获取 SimpleXml 属性

How to get SimpleXml attributes in PHP

我需要解析此 ECB currencies 费率。但是当我尝试访问属性时,我得到了一个空值。代码看起来像

$xml = new \SimpleXMLElement($xml);

/** @var \SimpleXMLElement $c */
foreach ($xml->Cube->Cube->Cube as $c)
{
    Debugger::log($c->attributes()->currency);  // OK
    Debugger::log($c->attributes()['currency']);  // OK
    Debugger::log('*************************');
    $this->currency->setCurrencyRate($c->attributes()->currency, $c->attributes()->rate);
}


public function setCurrencyRate($currency, $rate)
{
    $data = [
        'currency' => $currency,  // ERROR empty string
        'rate' => $rate,  // ERROR empty string
        'updated' => new \DateTime(),
    ];
    $this->db->query('INSERT INTO currencies_rates ', $data, ' ON DUPLICATE KEY UPDATE currency = ', $currency, ' rate = ', $rate, 'updated = ', new \DateTime());
}

这是xml

<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
    <gesmes:subject>Reference rates</gesmes:subject>
    <gesmes:Sender>
        <gesmes:name>European Central Bank</gesmes:name>
    </gesmes:Sender>
    <Cube>
        <Cube time="2021-12-13">
            <Cube currency="USD" rate="1.1278"/>
            <Cube currency="JPY" rate="128.19"/>
            <Cube currency="BGN" rate="1.9558"/>
            <Cube currency="CZK" rate="25.401"/>
            <Cube currency="DKK" rate="7.4362"/>
            <Cube currency="GBP" rate="0.85158"/>
            <Cube currency="HUF" rate="367.07"/>
            ...
        </Cube>
    </Cube>
</gesmes:Envelope>

没看懂

在 SimpleXML 中,几乎所有东西 returns 都是您可以与之交互的 SimpleXMLElement 对象。你可以用一个属性对象做很多事情,但是你可以这样写:

$currencyAttribute = $c->attributes()->currency;
echo $currencyAttribute->getName(); // 'currency'

为了获得元素或属性的文本内容,您必须将其转换为字符串。很多时候,您不会注意到这一点,因为当您将对象传递给 echo、像 'Currency: . $currencyAttribute 那样连接它、像 "Currency: $currencyAttribute" 那样插入它时,它会自动发生。但是有时你需要强制它成为一个字符串,然后再将它传递到某个地方,使用(string)语法(或strval()函数):

$this->currency->setCurrencyRate( (string) $c->attributes()->currency, (string) $c->attributes()->rate);