Parse RDF XML file to get all rdf:about values

2019-07-19 23:00发布

I am using php's simple xml and xpath to parse an rdf xml file and am struggling to get a list of all the rdf:about values.

Any advice?

1条回答
男人必须洒脱
2楼-- · 2019-07-19 23:22

There seems to be an issue when using SimpleXml with namespaced attributes prior to PHP5.3. Basically, anything with a : will be dropped when converted to an object property of a SimpleXml element. The following will do, but feels hackish to me:

$rdf = str_replace('rdf:about', 'rdf_about', $rdf);  
$rdf = new SimpleXMLElement($rdf);
foreach($rdf->xpath('//@rdf_about') as $node) {
  echo $node, PHP_EOL;
}

See here:

You could use DOM instead of SimpleXml:

$dom = new DomDocument;
$dom->loadXml($rdf);
$xph = new DOMXPath($dom);
$xph->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
foreach($xph->query('//@rdf:about') as $attribute) {
    echo $attribute->value, PHP_EOL;
}

But, I suggest using a dedicated library for this over SimpleXml or DOM:

And here's a blog post about the parsers:

查看更多
登录 后发表回答