Dennis
Dennis

Reputation: 1156

PHP json_encode not returning valid json

I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:

<?php
header('content-type: application/json; charset=utf-8');

if( strlen($_GET["feed"]) >= 13 ) {
  $xml = file_get_contents(urldecode($_GET["feed"]));
  if($xml) {
    $data = @simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($data);

    echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
  }
}
?>

The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..

Is there a way I can change these characters prior to sending back or pass json_encode options?

Upvotes: 2

Views: 9847

Answers (4)

Karolis
Karolis

Reputation: 9572

It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?

Upvotes: 0

Rukmi Patel
Rukmi Patel

Reputation: 2561

We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..

Upvotes: 0

Stefan Gehrig
Stefan Gehrig

Reputation: 83672

You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).

SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:

$json = json_encode(array($data));

Upvotes: 1

Berry Langerak
Berry Langerak

Reputation: 18859

You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):

$json = json_encode(array($data));

EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.

Upvotes: 1

Related Questions