1

I'm attempting to use php to grab xml from an API. So far I've looked at the following blog post and this previous stackoverflow post but am not having success.

The xml data is available here by viewing the source of the web page.

From my understanding php's json_encode returns the json data as string prepended by string(length).

What I'd like to do is to load the encoded json data with JQuery's $.ajax to manipulate the data with javascript. However the data returned from php's json_encode is not compatible with $.ajax.

Would anyone have any suggestions on how to format the string so that the data can be read by ajax?

update, my code php code is here:

<?php        

    $url = file_get_contents("http://api.wefeelfine.org:8080/ShowFeelings?display=xml&returnfields=sentence&limit=50");

    $simpleXml = simplexml_load_string($url);

    $json = json_encode($simpleXml);

    var_dump($json);

?>

I'm using php to do a cross-domain request, then using the url for the php code with $.ajax. When using $.ajax to access the API's url without php I get a No 'Access-Control-Allow-Origin' error.

Community
  • 1
  • 1
clhenrick
  • 798
  • 6
  • 13

1 Answers1

0

json_encode won't work on a SimpleXMLElement object, at least not as you would expect it. Try preprocessing your XML like so:

$feelings = array();
foreach($simpleXml as $feeling) {
    $feelings[] = array('sentence' => $feeling['sentence'] . '');
}
$json = json_encode($feelings);
Samuel
  • 2,106
  • 1
  • 17
  • 27
  • thanks Samy. Looks like that works! Though I realized that the data I'd like contains multiple tags where as the url above only has a single tag (sentence). Is there a way I could return multiple tags? For example in [this url](http://api.wefeelfine.org:8080/ShowFeelings?display=xml&returnfields=imageid,feeling,sentence,posttime,postdate,posturl,gender,born,country,state,city,lat,lon,conditions&limit=500) – clhenrick Dec 11 '13 at 01:21