2

I'm trying to return an array in HTTP response. I'm thinking to return array as JSON objects. I'm doing echo json_encode($arr) but I get nothing in the response.

UPDATE: I'm running a version of PHP that does not have json_encode method. json_encode was introduced in PHP 5.2. So I guess question is how would you return an array without using json_encode?

     $arr = array();
    foreach($_POST['ids'] as $id)
    {
        $arr[$id] = $id;
    }   
    echo json_encode($arr);

    return;

Here are contents of my array:

array(18) {
  [156795]=>
  string(6) "156795"
  [156800]=>
  string(6) "156800"
  [4292]=>
  string(4) "4292"
  [796053]=>
  string(6) "796053"
  [660520]=>
  string(6) "660520"
 ...
3
  • 1
    Show us your actual code. We can't debug based on your short description. Commented Sep 28, 2011 at 22:10
  • 1
    JSON is definitely the right method. But nothing is wrong here. Show your javascript, and your full server-side method. Commented Sep 28, 2011 at 22:11
  • I updated question with more of my code. Commented Sep 28, 2011 at 22:15

4 Answers 4

3

Make sure to set the proper MIME type when sending back JSON:

header('Content-Type: application/json');
echo json_encode($arr);
Sign up to request clarification or add additional context in comments.

Comments

2

json_encode() requires PHP 5.2.0 or above. Make sure your host hasn't compiled PHP with the --disable-json flag. Both of these can be checked with the phpinfo() function. The code you've posted so far works fine for me.

3 Comments

Looks like this is it. I have PHP Version 5.1.4 running. What is the next best thing to do in order to return an array?
You could use a json_encode() alternative - e.g. mike-griffiths.co.uk/php-json_encode-alternative
sorry i'm new to php but how would you return array before php 5.2? would you use something like serialize?
0

json encode should do it with no problems. When I pump that data into an array it works fine. Can you post some code for building the array? What version of PHP are you using?

Comments

0

plz use json validator to make sure ur json is correct

look I did this & it worked fine

 $arr = array();
 $i=0;
    while($i<10)
    {
        $arr[$i] = $i;
        $i++;
    }   
    echo json_encode($arr);

    return;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.