使用 SimpleXML 解析 PHP 中嵌套的 XML/RDF 命名空间元素 [英] Parsing nested XML/RDF namespace elements in PHP with SimpleXML
问题描述
鉴于下面的 XML/RDF 示例取自 来自 W3C 网站,我该如何访问cd"命名空间中的值?
Given the XML/RDF example below taken from the W3C website, how can I access the values in the "cd" namespace?
<?xml version="1.0"?>
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cd="http://www.recshop.fake/cd#">
<rdf:Description
rdf:about="http://www.recshop.fake/cd/Empire Burlesque">
<cd:artist>Bob Dylan</cd:artist>
<cd:country>USA</cd:country>
<cd:company>Columbia</cd:company>
<cd:price>10.90</cd:price>
<cd:year>1985</cd:year>
</rdf:Description>
</rdf:RDF>
我尝试过以下操作:
$XML = new SimpleXMLElement($rawXML); // Assume $rawXML is the quoted XML/RDF above
foreach($xml as $entry){
$cd = $entry->children('http://www.recshop.fake/cd#');
echo $cd->artist;
echo $cd->$country;
...
}
我也试过这样做:
$XML = new SimpleXMLElement($rawXML); // Assume $rawXML is the quoted XML/RDF above
foreach($xml as $entry){
$cd = $entry->children('http://www.recshop.fake/cd#');
$rdf = $entry->children('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
echo $rdf->$cd->artist;
echo $rdf->$cd->$country;
...
}
此外,在 PHP 中,如果不是声明 xmlns:cd="http://www.recshop.fake/cd#"
它是 xmlns=http://www.recshop.fake/cd#"
和cd"命名空间已从
等中删除.
Also, in PHP is it necessary to do anything different if instead of declaring xmlns:cd="http://www.recshop.fake/cd#"
it were xmlns="http://www.recshop.fake/cd#"
and the "cd" namespace was removed from <cd:artist>
, etc.
推荐答案
可以使用 xpath,首先需要注册命名空间.试试这个:
You can use xpath, first you need to register the namespaces. Try this:
$xml = new SimpleXMLElement($rawXML);
$xml->registerXPathNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
$xml->registerXPathNamespace('cd', 'http://www.recshop.fake/cd#');
$cd = $simple->xpath('rdf:Description/cd:*');
$cd 将是一个 SimpleXMLElements 数组.
$cd will be an array of SimpleXMLElements.
这篇关于使用 SimpleXML 解析 PHP 中嵌套的 XML/RDF 命名空间元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!