在PHP中的SimpleXMLElement中访问@attributes数据

时间:2011-09-23 00:32:24

标签: php xml

刚开始说我已经在这个网站上阅读了很多关于这个确切问题的问题,但我仍然在努力将它应用到我的场景中。如果有人可以帮助我,那就太好了! :)

我正在尝试从以下XML中提取数据:

$myXML = '<?xml version="1.0" encoding="UTF-8"?>
<products><product uri="https://192.168.110.201:9630/api/products/1807/" id="1807"    resource_type="current"><code>DEMO - MC700X/A</code><flags><inventoried>true</inventoried><editable_sell>false</editable_sell><master_model>false</master_model></flags><sell_price>0.00</sell_price><description>Apple MC700X/A Demo</description><inventory><available>7</available><reserved>0</reserved><coming_for_stock>2.0</coming_for_stock><coming_for_customer>0.0</coming_for_customer><warehouses>0</warehouses><total>7</total></inventory><product_photos/></product></products>';

我正在使用SimpleXML将它放入PHP变量(对象?)中,如下所示:

$xml = new SimpleXMLElement($myXML);

如果我这样做:

echo '<pre>';
print_r($xml);
echo '</pre>';

我收到以下内容:

SimpleXMLElement Object
(
    [product] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [uri] => https://192.168.110.201:9630/api/products/1807/
                    [id] => 1807
                    [resource_type] => current
                )

            [code] => DEMO - MC700X/A
            [flags] => SimpleXMLElement Object
                (
                    [inventoried] => true
                    [editable_sell] => false
                    [master_model] => false
                )

            [sell_price] => 0.00
            [description] => Apple MC700X/A Demo
            [inventory] => SimpleXMLElement Object
                (
                    [available] => 7
                    [reserved] => 0
                    [coming_for_stock] => 2.0
                    [coming_for_customer] => 0.0
                    [warehouses] => 0
                    [total] => 7
                )

            [product_photos] => SimpleXMLElement Object
                (
                )

        )

)

现在,当我尝试以编程方式访问该数据时,以下工作正常:

// This returns the value as expected
echo '<pre>';
echo($xml->product->code);
echo '<br>';
echo($xml->product->sell_price);
echo '<br>';
echo($xml->product->inventory->available);
echo '<br>';
echo '</pre>';

返回:

DEMO - MC700X/A
0.00
7

但我需要能够访问基本“product”元素中的“id”标记(即@attributes位),但无法解决它。我一直在阅读,并认为我应该能够使用attributes()方法,但我无法完全解决它。

尝试这个不起作用:

echo '<pre>';
echo($xml->attributes());
echo '<br>';
echo '</pre>';

它什么都不返回。有人可以帮帮我吗?我希望能够显示“id”标签..即我期望的是:

echo $xml['product']['@attributes']['id'];

显然也不起作用。

谢谢! 约翰

2 个答案:

答案 0 :(得分:54)

你有没有尝试过:

echo (string)$xml->product->attributes()->id;

这应该可以让您访问属性。

如果您有多个产品,则可能是

echo (string)$xml->product[0]->attributes()->id;

您还可以使用常规数组表示法访问属性,例如:

$xml->product['id']; // instead of $xml->product->attributes()->id

有关详细信息,请参阅SimpleXML示例中的Example #5以及SimpleXMLElement::attributes()上的手册页。

答案 1 :(得分:0)

$array = (array)$obj;
$prop_id = $array['@attributes'];