2011-09-23 70 views
24

只是想開始說我閱讀本網站上有關此確切問題的很多問題,但我仍然努力將其應用於我的方案。如果有人能幫助我,那太棒了! :)在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']; 

顯然不起作用。

謝謝! 約翰

+0

[從SimpleXML的訪問@attribute]的可能重複(http://stackoverflow.com/questions/1652128/accessing-attribute-from-simplexml) – hakre

回答

53

你嘗試:

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

這應該給你訪問的屬性。

如果你有超過1個產品,也可能是

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

您也可以訪問使用規則排列的符號的屬性,如:

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

請參閱從SimpleXML的例子Example #5以及有關SimpleXMLElement::attributes()的手冊頁以獲取更多信息。

+0

德魯,你是男人!非常感謝。我曾嘗試過,但看起來我需要將結果作爲字符串來顯示,我猜。 :) –

+0

是的,這可能很煩人,很容易忘記,如果你沒有演員訪問它,你仍然應該得到一個值,但它是一個SimpleXMLElement,所以在某些情況下嘗試使用它是行不通的。 – drew010

+2

也考慮到使用['@attributes']您需要將SimpleXMLElement強制轉換爲數組 – Enrique

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