2011-05-07 38 views
0

我已經閱讀了大約數百個關於該命令的SO條目,但是我無法使其工作。我真的不明白我做錯了什麼。我確實在做一些明顯愚蠢的事情,但目前我看不到它。SimpleXMLElement:正在檢索命名空間屬性

我試圖解析http://api.spreadshirt.net/api/v1/shops/614852/productTypes?locale=de_DE&fullData=false&limit=20&offset=0

這是我在做什麼:

$shopUrl = "http://api.spreadshirt.net/api/v1/shops/614852/productTypes?". 
    "locale=de_DE&fullData=false&limit=20&offset=0" 


$ch = curl_init($shopUrl); 
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HEADER, false); 
$result = curl_exec($ch); 
curl_close($ch);  

$products = new SimpleXMLElement($result); 

foreach ($products->productType as $product) { 
    $resources = $product->children('http://www.w3.org/1999/xlink'); 
    $resEntity = array(
     'id' => (int)$product->attributes()->id, 
     'name' => (string)$product->name[0], 
     'price' => (string)$product->price[0]->vatIncluded[0], 
     'preview' => $resources 
    ); 
    echo '<pre>'.print_r($resEntity, true).'</pre>';  
} 

此輸出我

Array 
(
    [id] => 6 
    [name] => Männer T-Shirt klassisch 
    [price] => 9.90 
    [preview] => SimpleXMLElement Object 
     (
      [@attributes] => Array 
       (
        [href] => http://api.spreadshirt.net/api/v1/shops/614852/productTypes/6 
       ) 

     ) 

) 

現在我試圖訪問HREF-屬性,但我試過的所有東西,如$resources->attributes()->href$resources['href'],但PHP繼續說Node no longer exists

回答

1

您必須在attributes()方法中指定命名空間。我猜(在attributes()的手冊中沒有詳細說明),你必須用第一個參數指定xml命名空間。這可能會從xlink命名空間獲得href屬性。否則,您只需從默認的 xml名稱空間獲取屬性,即typemediaType(或您從中獲取屬性的節點)。

它應該是這樣的工作(未測試):

$resources = $product->resources[0]; // <resources> node 
$resource = $resources->resource[0]; // first <resource> node 
$attribs = $resource->attributes('http://www.w3.org/1999/xlink'); // fetch all attributes from the given namespace 
var_dump($attribs->href); // or maybe var_dump((string)$attribs->href); 
+0

謝謝!這像一個魅力。 ''preview'=>(string)$ attribs-> href [0]' – marekventur 2011-05-07 15:32:59