PHP simplexml: why does xpath stop working?

前端 未结 1 715
你的背包
你的背包 2020-12-10 13:49

A strange thing happened after a supplier changed the XML header a bit. I used to be able to read stuff using xpath, but now I can\'t even get a reply with

$         


        
相关标签:
1条回答
  • 2020-12-10 14:09

    Most likely this is because they've introduced a default namespace (xmlns="http://iptc.org/std/NewsML/2003-10-10/") into their document. SimpleXML's support for default namespaces is not very good, to put it mildly.

    Can you try to explicitly register a namespace prefix:

    $xml->registerXPathNamespace("n", "http://iptc.org/std/NewsML/2003-10-10/");
    $xml->xpath('/n:NewsML');
    

    You would have to adapt your XPath expressions to use the "n:" prefix on every element. Here is some additional info: http://people.ischool.berkeley.edu/~felix/xml/php-and-xmlns.html.

    EDIT: As per the spec:

    The registerXPathNamespace() function creates a prefix/ns context for the next XPath query.

    This means it would have to be called before every XPath query, thus a function to wrap XPath queries would be the natural thing to do:

    function simplexml_xpath_ns($element, $xpath, $xmlns)
    {
        foreach ($xmlns as $prefix_uri)
        {
            list($prefix, $uri) = explode("=", $prefix_uri, 2);
            $element->registerXPathNamespace($prefix, $uri);
        }
        return $element->xpath($xpath);
    }
    

    Usage:

    $xmlns = ["n=http://iptc.org/std/NewsML/2003-10-10/"];
    $result = simplexml_xpath_ns($xml, '/n:NewsML', $xmlns);
    
    0 讨论(0)
提交回复
热议问题