php - Simplexml XPath 异常

标签 php xml dom xpath kml

我正在编写一个读取和操作 KML (xml) 文档的脚本。以下是我正在阅读的文档的片段:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by Feature Manipulation Engine 2009 (Build 5658) -->
<kml xmlns="http://earth.google.com/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
    <Document>
        <name>South Australia</name>
        <visibility>1</visibility>
        <description><![CDATA[Statistical Local Area 2008]]></description>
        <Folder id="kml_ft_SA_SLA08">
            <name>SA_SLA08</name>
            <Placemark id="kml_1">
                <name>Mitcham (C) - West</name>
                <Style>
                    <!-- style info blah blah -->
                </Style>
                <Polygon>
                    <!-- blah blah -->
                </Polygon>
            </Placemark>

            <!-- snip lots more Placemarks -->
        </Folder>
    </Document>
</kml>

我遇到的问题是使用 XPath 从中选择任何内容!
$doc = new DOMDocument();
$doc->load('myfile.xml');    // returns true
$xp = new DOMXPath($doc);

$places = $xp->query("//Placemark");
echo $places->length;         // --> 0 ??!!??
$everything = $xp->query("//*"); // (so I know that the XPath isn't fully borked)
echo $everything->length;    // --> 2085 

这里发生了什么?

最佳答案

<?php
$doc = new DOMDocument();
$doc->load('file.xml');    // returns true
$xp = new DOMXPath($doc);
$xp->registerNamespace('ge', 'http://earth.google.com/kml/2.2');

$places = $xp->query("//ge:Placemark");
echo $places->length;         // --> 0 ??!!??
$everything = $xp->query("//*"); // (so I know that the XPath isn't fully borked)

//echo $doc->saveXML();

显然你必须注册'ge'命名空间并查询它,至少这是我在谷歌搜索几分钟后想出的。我想有时我们会忘记我们正在处理命名空间:p

关于php - Simplexml XPath 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1464099/

相关文章:

java - DOM XML Public Doctype 未出现在结果 xml 文件中

javascript - JQuery .change(function..) 在 DataTables 第 2 页或第 11 行之后不起作用

xml - 导入命名空间的 Eclipse WSDL 验证错误

xml - 如何使用 XSLT 对值进行排序?

javascript - 在 contenteditable div 中保持光标位置

javascript - Div 是空的,即使它有一个 child

php - CodeIgniter 在同一 Controller 中加载多个模型

php - 如何添加具有相同值的查询行?

php - 使用 PHP 通过 IP 地址获取国家/地区、GMT、城市

java - XSD 验证错误 : Cannot find the declaration of element 'xs:schema'