无法通过PHP中的simplexml_load_file读取XML

时间:2013-10-02 03:56:25

标签: php xml simplexml

我试图读取一个xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<!-- UNCLASSIFIED -->

<!-- Built from ANZLIC MET Template ISO 19139 2009-02-18 -->
-<gmd:MD_Metadata xsi:schemaLocation="http://www.isotc211.org/2005/gmd http://www.isotc211.org/2005/gmd/gmd.xsd http://www.opengis.net/gml http://www.isotc211.org/2005/gml/gml.xsd http://www.w3.org/1999/xlink http://www.isotc211.org/2005/xlink/xlinks.xsd" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gts="http://www.isotc211.org/2005/gts" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:gmd="http://www.isotc211.org/2005/gmd">
<!--METValidation=False-->
-<gmd:fileIdentifier> <gco:CharacterString>D09C1546-5CB8-49AE-B717-E74FF3499F57</gco:CharacterString> </gmd:fileIdentifier>
 ...
 ...
 ...

我使用了$xml = simplexml_load_file($_FILES["file"]["tmp_name"]);,但我遇到了名称空间和冒号问题!

有人可以帮我解读这个XML吗?!

干杯, Arash的

1 个答案:

答案 0 :(得分:0)

尝试$xml = simplexml_load_file($_FILES["file"]["tmp_name"], null, null, null, true);

如果不起作用,请阅读here。此方法/函数的最后一个参数是名称空间。鉴于此XML文档有很多,最好只使用SimpleXML类。

@IMSoP是绝对正确的;这是因为你必须注册XpathNamespaces。

'file.xml'中的XML:     

<!-- UNCLASSIFIED -->

<!-- Built from ANZLIC MET Template ISO 19139 2009-02-18 -->
<gmd:MD_Metadata xsi:schemaLocation="http://www.isotc211.org/2005/gmd http://www.isotc211.org/2005/gmd/gmd.xsd http://www.opengis.net/gml http://www.isotc211.org/2005/gml/gml.xsd http://www.w3.org/1999/xlink http://www.isotc211.org/2005/xlink/xlinks.xsd" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:gts="http://www.isotc211.org/2005/gts" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:gmd="http://www.isotc211.org/2005/gmd">
<!--METValidation=False-->
<gmd:fileIdentifier> <gco:CharacterString>D09C1546-5CB8-49AE-B717-E74FF3499F57</gco:CharacterString> </gmd:fileIdentifier>
</gmd:MD_Metadata>

PHP:

<?php

$xml = simplexml_load_file("file.xml");

$xml->registerXPathNamespace("gmd", "http://www.isotc211.org/2005/gmd");
$xml->registerXPathNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
$xml->registerXPathNamespace("gco", "http://www.isotc211.org/2005/gco");
print_r($xml->xpath("//gco:CharacterString"));

输出:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => D09C1546-5CB8-49AE-B717-E74FF3499F57
        )

)