simplexml_load_file无法识别< dc:title>标签 [英] simplexml_load_file does not recognize <dc:title> tags

查看:176
本文介绍了simplexml_load_file无法识别< dc:title>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用simplexml_load_file()加载XML文件并到达<dc:title>标签,但是当我转储加载了xml文件的$xml变量时,所有以<dc:开头的标签都没有显示.有没有办法告诉解析器包括它们?我应该使用其他解析器吗?

I am trying to use simplexml_load_file() to load an XML file and reach <dc:title> tags, but when I dump the $xml variable that loaded my xml file all the tags that starts with <dc: doesn't show. Is there a way of telling the parser to include them? should I use a different parser?

这是我的示例文件的代码:

Here's my example file's code:

<?xml version='1.0' encoding='utf-8'?>
<package xmlns="http://www.idpf.org/2007/opf" prefix="ibooks: http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0/" unique-identifier="pub-id" version="3.0" xml:lang="en">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:title>test</dc:title>
  </metadata>
</package>

我用来检查可见标签的代码:

Code I used to check for which tags are seen:

$xml = simplexml_load_file('test.xml');
echo '<pre>';var_dump($xml);echo '</pre>';

结果:

object(SimpleXMLElement)#1 (2) {
  ["@attributes"]=>
  array(3) {
    ["prefix"]=>
    string(80) "ibooks: http://vocabulary.itunes.apple.com/rdf/ibooks/vocabulary-extensions-1.0/"
    ["unique-identifier"]=>
    string(6) "pub-id"
    ["version"]=>
    string(3) "3.0"
  }
  ["metadata"]=>
  object(SimpleXMLElement)#2 (0) {
  }
}

元数据实际上是空的.有想法吗?

metadata is in fact, empty. Thoughts?

推荐答案

首先,dc是名称空间,不是标记名的一部分.出于测试目的,您可以打印给定xml中使用的名称空间.执行代码段

First, dc is a namespace, not part of tag name. For testing purpose you can print the namespaces used in the given xml. Executing the snippet

$namespaces = $xml->getNamespaces(true);
var_dump($namespaces);

将输出

array(3) {
  '' =>
  string(28) "http://www.idpf.org/2007/opf"
  'xml' =>
  string(36) "http://www.w3.org/XML/1998/namespace"
  'dc' =>
  string(32) "http://purl.org/dc/elements/1.1/"
}

您必须注册用于xpath的名称空间的前缀,然后才能使用它进行选择:

You have to register a prefix for the namespace for usage with xpath, then you can use it for selection:

$xml->registerXPathNamespace('b', 'http://purl.org/dc/elements/1.1/');
$a =$xml->xpath('//b:*/text()');
foreach($a as $t) {
   print($t."\n");
}

这将输出要获取的元素的test.

This will output test of the element you want to get.

这篇关于simplexml_load_file无法识别&lt; dc:title&gt;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆