SimpleXML问题打印键值


SimpleXML problem print key value

我已经在谷歌上搜索了一个多小时了,我很沮丧,这看起来很简单。我要打印的只是我的accountId。下面是我从服务器返回的xml:

SimpleXMLElement Object
(
[accounts] => SimpleXMLElement Object
    (
        [account] => SimpleXMLElement Object
            (
                [billingStreet] => SimpleXMLElement Object
                    (
                    )
                [billingCity] => SimpleXMLElement Object
                    (
                    )
                [billingState] => SimpleXMLElement Object
                    (
                    )
                [billingPostalCode] => SimpleXMLElement Object
                    (
                    )
                [billingCountry] => SimpleXMLElement Object
                    (
                    )
                [city] => Los Angeles
                [accountId] => XXXXX
                [companyName] => SimpleXMLElement Object
                    (
                    )
                [country] => United States
                [email] => XXXXX
                [enabled] => 1
                [fax] => SimpleXMLElement Object
                    (
                    )
                [firstName] => XXXXX
                [lastName] => XXXXX
                [multiClientFolder] => 0
                [multiUser] => 0
                [phone] => XXXXX
                [postalCode] => XXXXX
                [state] => CA
                [street] => XXXXX
                [title] => SimpleXMLElement Object
                    (
                    )
                [accountType] => 0
                [subscriberLimit] => 250000
            )
    )
[total] => 1
[limit] => 20
[offset] => 0
)

我想要的是accountId。我正在使用这个,它不打印任何东西:

$ch=curl_init("https://app.sandbox.icontact.com/icp/a/");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$buf = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($buf);
$aid=$xml->$accounts->$account->$accountId;
print($aid);

我可以用print_r打印整个XML数组。我不知道我做错了什么

也许$aid=$xml->accounts->account->accountId;?

如果有可能在响应中获得多个帐户,则可以向帐户元素添加数组索引:

$aid = $xml->accounts->account[0]->accountId;

或遍历帐户:

foreach ($xml->accounts->account as $account) {
    ...
}

还要注意$aid的类型是SimpleXMLElement。在大多数情况下,您可以按原样使用它,它将自动转换为适当的类型,但如果您希望将值转换为字符串,则可以使用显式转换:

$aid = (string) $xml->accounts->account[0]->accountId;