【问题标题】:SimpleXML failing to find namespaced elementsSimpleXML 找不到命名空间元素
【发布时间】:2010-12-28 18:44:58
【问题描述】:

我似乎无法让 PHP 的 SimpleXML 类识别 XHTML 文档中的前缀命名空间元素。这是我的例子:

test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:zuq="http://localhost/zuq">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
    <h1>Heading</h1>
    <p>Paragraph</p>
    <zuq:region name="myRegion">
        <div class="myClass">
            <h1><zuq:data name="myDataHeading" /></h1>
            <p><zuq:data name="myDataParagraph" /></p>
        </div>
    </zuq:region>
</body>
</html>

当我执行以下操作时:

$sxml = simplexml_load_file('test.html');
print_r($sxml);

返回:

SimpleXMLElement Object
(
    [head] => SimpleXMLElement Object
        (
            [meta] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [http-equiv] => Content-Type
                            [content] => text/html; charset=utf-8
                        )

                )

            [title] => Untitled Document
        )

    [body] => SimpleXMLElement Object
        (
            [h1] => Heading
            [p] => Paragraph
        )

)

但是当我执行以下操作时:

$sxml = simplexml_load_file('test.html');
$sxml_zuq = $sxml->children('zuq', true);
print_r($sxml_zuq);

返回空:

SimpleXMLElement Object
(
)

使用 foreach 或其他方式遍历对象似乎不起作用,并且使用 URI 而不是 children() 中的前缀也会失败。

我显然在某个地方犯了错误,但我不确定在哪里,因为我的尝试与我在阅读中遇到的许多教程示例完全相同。

这是怎么回事?

【问题讨论】:

  • 如果你使用SimpleXMLElement::getNamespaces(),你会得到结果吗?
  • 是的,我愿意约翰·乔塔;然而,正如 Josh 所指出的,孩子只是直系后代。

标签: php xml simplexml xml-namespaces


【解决方案1】:

children() 只为您提供上下文节点的 [直接] 子节点,而不是后代。

$html = simplexml_load_file('test.html');

// get <body/>'s children
$html->body->children('zuq', true);

// use XPath to get all zuq:* nodes
$html->xpath('//zuq:*');

【讨论】:

  • Josh Davis 拯救了一天 :)
【解决方案2】:

只是为了信息,如果命名空间定义 xmlns:zuq="http://localhost/zuq" 是在实际的 xml 元素而不是根节点中声明的,那么我们必须另外调用 registerXPathNamespace 函数然后使用 xpath如http://www.dimuthu.org/blog/2008/09/30/xpath-in-simplexml/中所述

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2015-12-06
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多