访问SimpleXMLElement对象值

时间:2012-07-29 16:29:30

标签: php xpath simplexml associative-array

我有以下SimpleXMLElement对象http://pastebin.com/qEP0UUPJ

我可以使用xpath $xaugbp = $xml->xpath("/query/results/rate");查询它,但这只会缩小搜索范围:

http://pastebin.com/Xwezx4bZ

我希望访问以下对象:

[0] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => XAUGBP
            )

        [Name] => XAU to GBP
        [Rate] => 1030.5784
        [Date] => 7/27/2012
        [Time] => 5:55pm
        [Ask] => 1027.5662
        [Bid] => 1033.5896

我可以使用

获取该特定对象
$ob = $xmlObject->xpath("//query/results/rate[contains(@id, 'XAUGBP')]");

我可以使用

来'询问'
$ob = $xmlObject->xpath("//query/results/rate[contains(@id, 'XAUGBP')]/Ask");

但是如何将该对象转换为变量。例如这样我可以对它进行计算吗?

xpath是唯一这样做的方法吗?有更好/更有效/更快的方式吗?是否可以将其转换为关联数组以便于访问?

2 个答案:

答案 0 :(得分:2)

<强>前言

在你做任何事情之前,(重新)熟悉SimpleXML独特的做事方式。最好的起点是SimpleXML basic usage手册页。


以下示例显示:

  • 根据属性的值获取单个<rate>元素对象,以及如何显示它。
  • 循环显示所有<rate>元素并显示其值。

基本示例代码

$query = simplexml_load_file('…');

// Get a <rate> element by its id attribute
$rates = $query->xpath('results/rate[@id = "XAUGBP"]');
$rate  = $rates[0];
echo "$rate->Name was at $rate->Rate at $rate->Time on $rate->Date\n";

echo "-----\n";

// or, loop over all of the <rate> elements
foreach ($query->results->rate as $rate) {
    echo "$rate->Name was at $rate->Rate at $rate->Time on $rate->Date\n";
}

以上示例输出:

XAU to GBP was at 1030.5784 at 5:55pm on 7/27/2012
-----
XAU to GBP was at 1030.5784 at 5:55pm on 7/27/2012
XAG to GBPZ 999 N was at 17.4502 at 5:55pm on 7/27/2012
XPT to GBPZ 999 was at 893.3414 at 5:55pm on 7/27/2012
XPD to GBP1 UZ was at 362.652 at 5:55pm on 7/27/2012

See this example running online


XML to array

我看到一次又一次地被问到这个问题。而不是将SimpleXMLElement个对象的树变成一些“友好”的数组,而是花时间学习如何使用SimpleXML:一旦完成,就没有必要采取转动对象的中间步骤进入数组使用。上面提到的“基本用法”页面可以帮到你,但要知道的关键点是:

  1. 子节点使用属性语法:$parent->child
  2. 属性使用数组样式语法:$element["attr_name"]
  3. 根据需要将对象投射为友好类型:(string) $element->child

答案 1 :(得分:1)

XPath查询应为"//query/results/rate[contains(@id, 'XAUGBP')]"