Php SimpleXMLElement:检索命名空间属性
我已经读过几百篇关于这方面的文章,但我无法让它发挥作用。我真的看不出我做错了什么。我肯定在做一些明显愚蠢的事情,但目前我看不出来 我在试着分析 这就是我正在做的:Php SimpleXMLElement:检索命名空间属性,php,namespaces,simplexml,Php,Namespaces,Simplexml,我已经读过几百篇关于这方面的文章,但我无法让它发挥作用。我真的看不出我做错了什么。我肯定在做一些明显愚蠢的事情,但目前我看不出来 我在试着分析 这就是我正在做的: $shopUrl = "http://api.spreadshirt.net/api/v1/shops/614852/productTypes?". "locale=de_DE&fullData=false&limit=20&offset=0" $ch = curl_init($shopUrl);
$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>';
}
我现在正试图访问HREF属性,但迄今为止我尝试过的一切,如
$resources->attributes()->HREF
或$resources['HREF']
,但PHP一直说节点不再存在
您必须在attributes()
方法中指定名称空间。我想(在的手册中没有详细解释)您必须使用第一个参数指定xml名称空间。这可能会从xlink
命名空间获得href
属性。否则,您只需从默认xml名称空间获取属性,即type
和mediaType
(或者从哪个节点获取属性)
它应该是这样工作的(未经测试):
$resources=$product->resources[0];//节点
$resource=$resources->resource[0];//第一节点
$attribs=$resource->attributes('http://www.w3.org/1999/xlink'); // 从给定命名空间获取所有属性
变量转储($attribs->href);//或者可能是var_dump((字符串)$attribs->href);
谢谢!这很有魅力<代码>'preview'=>(字符串)$attribs->href[0]
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
)
)
)
$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);