我有以下示例 XML 数据,我想使用 PHP 将其解析为 SimpleXML:
<?xml version="1.0" encoding="utf-8" ?> <ogr:FeatureCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ogr.maptools.org/ fire_districts.xsd" xmlns:ogr="http://ogr.maptools.org/" xmlns:gml="http://www.opengis.net/gml"> <gml:boundedBy> <gml:Box> <gml:coord><gml:X>112.921100000165</gml:X><gml:Y>-43.65832660868602</gml:Y></gml:coord> <gml:coord><gml:X>153.6407999999201</gml:X><gml:Y>-10.05939999961026</gml:Y></gml:coord> </gml:Box> </gml:boundedBy> <gml:featureMember> <ogr:IDM00007 fid="IDM00007.0"> <ogr:geometryProperty><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>153.551804332204,-28.1645084912738 153.586699999805,-28.2582999997451 153.573299999695,-28.3133 153.582500000375</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty> <ogr:AAC>NSW_FW001</ogr:AAC> <ogr:DIST_NO>1</ogr:DIST_NO> <ogr:DIST_NAME>Far North Coast</ogr:DIST_NAME> <ogr:STATE_CODE>NSW</ogr:STATE_CODE> <ogr:SOURCE>RFS</ogr:SOURCE> <ogr:GROUP_NAME xsi:nil="true"/> </ogr:IDM00007> </gml:featureMember> <gml:featureMember> <ogr:IDM00007 fid="IDM00007.1"> <ogr:geometryProperty><gml:Polygon><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>153.261225211474,-29.9401032948311 153.19820000033,-30.038899999935 153.20060000039,-30.1036999997551 153.214099999715</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></ogr:geometryProperty> <ogr:AAC>NSW_FW002</ogr:AAC> <ogr:DIST_NO>2</ogr:DIST_NO> <ogr:DIST_NAME>North Coast</ogr:DIST_NAME> <ogr:STATE_CODE>NSW</ogr:STATE_CODE> <ogr:SOURCE>RFS</ogr:SOURCE> <ogr:GROUP_NAME xsi:nil="true"/> </ogr:IDM00007> </gml:featureMember> </ogr:FeatureCollection>
我尝试了几种使用 SimpleXML 加载此 XML 的不同方法,但是每当我对数据执行 print_r 时,它只是空白:
<?php $data = file_get_contents("fire_districts.gml"); $xml = new SimpleXMLElement($data); $xml->registerXPathNamespace('f', 'http://ogr.maptools.org/'); $xml->registerXPathNamespace('g', 'http://www.opengis.net/gml'); $gml = $xml->xpath('/f:FeatureCollection/g:featureMember'); print_r($gml); ?>
输出如下:
Array ( [0] => SimpleXMLElement Object ( ) [1] => SimpleXMLElement Object ( ) [2] => SimpleXMLElement Object ( ) [3] => SimpleXMLElement Object ( ) ....
我需要更改什么才能成功将此 GML 数据加载到数组中?
干杯,迈克
您可以尝试使用“var_dump”打印“$data”变量的内容或 'echo' 看看它是否包含预期的数据。
其他
尝试使用 simplexml_load_string() 而不是 file_get_contents()。