Parse XML using PHP with multiple namespaces

651 views Asked by At

I have an xml file which i am having a hard time to correctly parse: I need to retrieve the Value from the xml file

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

Below is the code that I am running:

// 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";
}

Below is the empty object I am getting:

object (SimpleXMLElement)[3]
SimpleXMLElement Object ( )

Pls help.

1

There are 1 answers

3
Ohgodwhy On

That actually is not an empty object, and has methods against it. This is expected. If you did

echo $output->asXML(); 

You will see your XML string returned.

Now perform methods against this to iterate the data set and retrieve your specific values.

Also, if you're dealing with debugging simplexml frequently, consider this function