Parsing a XML file using simplexml_load_file retur

2019-05-10 06:05发布

问题:

 <?xml version="1.0" ?> 
  <aws:UrlInfoResponse xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/">
   <aws:Response xmlns:aws="http://awis.amazonaws.com/doc/2005-07-11">
    <aws:OperationRequest>
    </aws:OperationRequest>
    <aws:UrlInfoResult>
     <aws:Alexa>
      <aws:TrafficData>
       <aws:DataUrl type="canonical">google.com/</aws:DataUrl> 
       <aws:Rank>1</aws:Rank> 
      </aws:TrafficData>
     </aws:Alexa>
    </aws:UrlInfoResult>
    <aws:ResponseStatus xmlns:aws="http://alexa.amazonaws.com/doc/2005-10-05/">
     <aws:StatusCode>Success</aws:StatusCode> 
    </aws:ResponseStatus>
   </aws:Response>
  </aws:UrlInfoResponse>

All i want to parse is rank from this xml document. while trying so what iam doing is ...

        $xml= simplexml_load_file("path of the file saved");
        echo $xml->Response->UrlInfoResult->Alexa->TrafficData->Rank;

but i am getting a error doing so .it says

 Notice: Trying to get property of non-object in C:\wamp\www\SEO Stats[Only Testing]\Tools\web_worth.php on line 13

the error is in this line

 echo $xml->Response->UrlInfoResult->Alexa->TrafficData->Rank;
 this line is referred as line no 13..

回答1:

The parser was returning an empty object because according to the documentation you have to specify the prefixed namespace - so for example you want to use something like:

simplexml_load_file('/path/to/file.xml', null, null, 'aws', true);

working example



回答2:

You've probably got the result object nesting wrong, thus one of the objects in $xml->Response->UrlInfoResult->Alexa->TrafficData->Rank; is null. Try echoing every step separately:

echo $xml->Response;
echo $xml->Response->UrlInfoResult;
// etc ...

If the first echo returns nothing, then check if you need to output UrlInfoResponse instead or need to register namespaces first.



回答3:

Ok, this is too vague, but you can always print the $xml value to see if it is actually an object or not, sometimes happens that the path is wrong. Try this code to see if the xml document is actually loaded:

<?php

if (file_exists('/path/to/document.xml')) {
    $xml = simplexml_load_file('/path/to/document.xml');

    print_r($xml);
} else {
    exit('Failed to open /path/to/document.xml.');
}

?>

With this you should see the content of the xml document.