Tutorial :how can I parse xml data in php



Question:

I am trying to find out how this would work

For testing purposes, I have made two websites.

One is calling a REST service from the other

I pull the xml data with file_get_contents

if I echo it, I can see a string off data.

But how can I use simpelxml on it, extract data from the nodes themselves?

If I use simplexml_load_file($url), I get some error saying xml declaration only allowed at the start off the document?

I have this in my testfile

<?php    $url='http://www.woonbel.nl/gps/setgpsloc';  //not working  $xml =simplexml_load_file($url);       print_r($xml);    //just a string  $xml=file_get_contents($url);  echo "<h3>$xml</h3><br>";    ?>  

this was the xml I send.

I send this from a class file that I included in the top off my php file if I am sure the webservice is called, maybe that has someting to do with the declaration error?

header('Content-type: text/xml');  echo "<?xml version=\"1.0\"?>\n";  echo "<response>\n";  echo "\t<status>$status_code</status>\n";  echo "\t<fout>Geen</fout>\n";  echo "</response>";  

Thanks, Richard


Solution:1

Sounds like there is a blank line at the top of the file, when it should start with the xml declaration. For example:

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


Solution:2

Have you got empty lines before the declaration?


Solution:3

Your REST service should be returning XML contents, something like this:

<?xml version="1.0" encoding="utf-8"?>  <results>    <result>      <value awesome="true">LOLCATS</value>    </result>  </results>  

You'd then do something along these lines to consume that REST service on the other site:

$xml = simplexml_load_string(file_get_contents('http://example.com/rest.xml'));    foreach($xml->result as $result) {    $value = $result->value;    $awesome = $result->attributes()->awesome;    // do something here with our values and attributes  }  

The PHP docs for SimpleXML contain more complicated/real-world examples.

For your specific XML:

$xml = simplexml_load_string(file_get_contents('http://example.com/rest.xml'));    $status = $xml->status;  $fout = $xml->fout;  


Solution:4

The error message clearly states that there is a blank, line or character, at the beginning of the xml-data. That could be file-encoding -issue.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »