php - SimpleXMLElement : Retrieving Namespace Attribute

标签 php namespaces simplexml

我已经阅读了数百个关于此的 SO 条目,但我无法让它发挥作用。我真的看不出我做错了什么。我肯定在做一些明显愚蠢的事情,但目前我看不到。

我正在尝试解析 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 .

最佳答案

您必须在 attributes() 中指定命名空间方法。我猜(在 attributes() 的手册中没有详细解释)您必须使用第一个参数指定 xml 命名空间。这可能会让您获得 href来自 xlink 的属性命名空间。否则,您只需从默认的 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);

关于php - SimpleXMLElement : Retrieving Namespace Attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5920975/

相关文章:

php - Laravel 模型转换无法正常工作

php - 我怎样才能平均分割一组数字

intellij-idea - 在 IntelliJ/PhpStorm 中更改测试根路径/模式

php - SimpleXMLElement、xpath 和子元素

PHP SimpleXML - xpath 不起作用,但在在线生成器中它可以

php - 如何使用 XAMPP 从我的表单中获取信息以插入到 mySQL 数据库中?

php - 将两种类型的引号作为字符串的文本 block

namespaces - 在 TCL 中访问命名空间变量的最快方法

命名空间中的 C++ 前向声明和友元

php - 循环遍历 SimpleXMLElement 以访问属性