使用具有多个名称空间的PHP解析XML

时间:2014-11-25 08:34:57

标签: php xml soap cisco-axl

我有一个xml文件,我很难正确解析: 我需要从xml文件中检索值

<?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <soapenv:Body>
            <ns1:PerfmonCollectCounterDataResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://schemas.cisco.com/ast/soap/">
                <ArrayOfCounterInfo soapenc:arrayType="ns1:CounterInfoType[2]" xsi:type="soapenc:Array" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                    <item xsi:type="ns1:CounterInfoType">
                        <Name xsi:type="ns1:CounterNameType">\\172.16.106.18\Number of Replicates Created and State of Replication(ReplicateCount)\Number of Replicates Created</Name>
                        <Value xsi:type="xsd:long">603</Value>
                        <CStatus xsi:type="xsd:unsignedInt">1</CStatus>
                    </item>
                    <item xsi:type="ns1:CounterInfoType">
                        <Name xsi:type="ns1:CounterNameType">\\172.16.106.18\Number of Replicates Created and State of Replication(ReplicateCount)\Replicate_State</Name>
                        <Value xsi:type="xsd:long">2</Value>
                        <CStatus xsi:type="xsd:unsignedInt">1</CStatus>
                    </item>
                </ArrayOfCounterInfo>
            </ns1:PerfmonCollectCounterDataResponse>
        </soapenv:Body>
    </soapenv:Envelope>

以下是我正在运行的代码:

// fclose($fopen);
// if (file_exists($filename)) {    
    // $output = simplexml_load_file($filename,null,null,"http://www.w3.org/2001/XMLSchema-instance",true);  // I have also tried without the namespaces
    ;
    //$output = simplexml_load_string($xmldata);

    //var_dump($output);
    //print_r($output);     
} else {
    echo "File not found";
}

下面是我得到的空对象:

object (SimpleXMLElement)[3]
SimpleXMLElement Object ( )

请帮助。

1 个答案:

答案 0 :(得分:0)

实际上它不是一个空对象,并且有针对它的方法。这是预料之中的。如果你做了

echo $output->asXML(); 

您将看到返回的XML字符串。

现在对此执行方法来迭代数据集并检索您的特定值。

此外,如果您经常处理调试simplexml,consider this function