Question

J'écris un script qui lit et manipule un document KML (XML). Vous trouverez ci-dessous un extrait du document que je lis:

<?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>

Le problème que j'ai est d'utiliser XPath pour en sélectionner quoi que ce soit!

$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 

Que se passe t-il ici?

Était-ce utile?

La solution

<?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();

Apparemment, vous devez enregistrer l'espace de noms «GE» et l'interroger en tant que tel, au moins c'est ce que j'ai trouvé après quelques minutes sur Google. Je suppose que parfois nous oublions que nous avons affaire à des espaces de noms: P

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top