只是想開始說我有閱讀本網站上有關此確切問題的很多問題,但我仍然努力將其應用於我的方案。如果有人能幫助我,那太棒了! :)在PHP中訪問SimpleXMLElement中的@attributes數據
我試圖從以下XML數據:我使用SimpleXML來把它變成一個PHP變量(對象?)這樣
$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>';
:
$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
但我需要能夠訪問「身份證」標記在基本的「產品」元素中(即, @attributes位),但無法解決問題。我一直在閱讀很多東西,並認爲我應該能夠使用attributes()方法,但我無法完全解決它。
嘗試並沒有工作:
echo '<pre>';
echo($xml->attributes());
echo '<br>';
echo '</pre>';
它只是沒有返回。有人可以幫幫我嗎?我希望能夠顯示「id」標籤..也就是我所期望的:
echo $xml['product']['@attributes']['id'];
顯然不起作用。
謝謝! 約翰
[從SimpleXML的訪問@attribute]的可能重複(http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml) – hakre