开发者

SimpleXMLElement: Retrieving Namespace Attribute

开发者 https://www.devze.com 2023-03-03 08:13 出处:网络
I\'ve read about hundreds of SO-entries about that, but I can\'t get it to work. I can\'t really see what I\'m doing wrong. I\'m most certainly doing something obviously stupid, but at the moment I ca

I've read about hundreds of SO-entries about that, but I can't get it to work. I can't really see what I'm doing wrong. I'm most certainly doing something obviously stupid, but at the moment I can't see it.

I'm trying to parse http://api.spreadshirt.net/api/v1/shops/614852/productTypes?locale=de_DE&fullData=false&limit=20&offset=0

This is what I'm doing:

$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>';    
}

This outputs me

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

        )

)

I'm now trying to access the HREF-attribute but everything I've tried so far like $resources->attributes()->href or $resources['href'] but PHP keeps on saying Node no longer exists.


You must specify the namespace in the attributes() method. I guess (it's not explained in detail in the manual of attributes()) you have to specify the xml namespace with the first argument. This might get you the href attribute from the xlink namespace. Otherwise you just get the attributes from the default xml namespace, namely type and mediaType (or from which node you fetch the attributes).

It should be work like this (not tested):

$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

精彩评论

暂无评论...
验证码 换一张
取 消