开发者

SimpleXML failing to find namespaced elements

开发者 https://www.devze.com 2023-02-01 18:39 出处:网络
I can\'t seem to get PHP\'s SimpleXML class to recognize prefixed namespace elements in an XHTML document. Here\'s my example:

I can't seem to get PHP's SimpleXML class to recognize prefixed namespace elements in an XHTML document. Here's my example:

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>

When I do the following:

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

It returns:

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
        )

)

But when I do the following:

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

It returns empty:

SimpleXMLElement Object
(
)

Iterating through the object with foreach or otherwise doesn't seem to work, and using the URI rather than the prefix in children() also fails.

I've obviously m开发者_开发知识库ade a mistake somewhere, but I'm not sure where, as my attempt is quite identical to many tutorial examples I've come across in my reading.

What's going on here?


children() only gives you the [direct] children of the context node, not descendants.

$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:*');


Just for Info, in case the namespace definition , xmlns:zuq="http://localhost/zuq" was declared in the actual xml element instead of root node, then we have to additionally call registerXPathNamespace function and then use xpath as given in http://www.dimuthu.org/blog/2008/09/30/xpath-in-simplexml/

0

精彩评论

暂无评论...
验证码 换一张
取 消