如何将PHP数组转码为JSON数组?

UPDATE: Based on suggestions here, I've modified my code. To get a handle on how this works, I am only trying to alert the PHP array with JSON. Still cannot get it to work. The code below resides on the same test.php page. If refreshed, should the alert fire? The function seems to fail as well. The TEST alert does not work.

<?php
  header('Content-type: application/json');
  $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
  echo json_encode($arr);
?>

<script type="text/javascript">
  $(function() {
    $.getJSON('test.php',function(data) {
      alert("TEST");

      $.each(data, function(key, item) {
        alert(key + item); }); 
      });
    });
  });
</script>

I am new to JSON and trying to get a PHP array to display in an HTML file. Below is a simple example. Please tell me if this should work and what I am doing wrong. I am trying to output the keys in this array. Thanks.

My PHP script (test.php):

     $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
json_encode($arr);

$content = file_get_contents('test.htm');
echo $content;

My HTML page (test.htm):

<script type="text/javascript">

  $(function() {
$.getJSON('test.php',function(data) {
  $.each(data,function(i, item) {
    alert(item.key);
      });
   });
});

 </script>

Make sure you have included jQuery in your HTML file.

As you are only alerting keys, you don't have to wait for a dom-ready event - and even if you wanted to, I would first get the JSON and put the $(function... into the ajax callback.

Your JSON-encoded PHP-array should look like this:

{"item1":"test1","item2":"test2","item3":"test3"}

Check about this in your debugger, or load test.php directly in your browser. As others have suggested, your PHP code with the file_get_contents is a bit odd.

Last, your object traversal won't work. Look at the docs:

$.each(data, function(key, item) {
    alert(key + item);
});

The string concatenator in JavaScript is the +, not the . as in PHP. item.key would try to access the key property of one of your items - none has such one as thy are strings.

It's enought to:

header('Content-type: application/json');
$arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
echo json_encode($arr);
exit;

Then your $.getJSON will get data.

WHy do you do a file_get_content() of the file which call your php page?

You shouldn't display it, but you should instead display your json data :

$arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
$content = json_encode($arr);

echo $content;

No that would not work.

first, make your php echo your array:

$arr = array('item1'=>"test1", 'item2'=>"test2", 'item3'=>"test3");
echo json_encode($arr);

Then call your javascript ajax function, and observe the response

<script type="text/javascript">
  $(function() {
$.getJSON('test.php',function(data) {
  $.each(data,function(i, item) {
    alert(item.key);
      });
   });
});
 </script>

It's because you don't need to do that last part in php where you call file_get_contents.

On your php, you can just do

$arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
echo json_encode($arr);

in Javascript, you're going to get back a Javascript object, and a simple way to iterate through the keys is

for(var key in data)
{
    alert(key + ' => ' + data[key]);
}

The problem is on your PHP script

json_encode($arr);

is not doing anything, theres no output or saving in a variable

and what is that you are getting from test.htm ? You can't put two different contents in a JSON to be parsed later by the $.getJSON, your PHP script should output ONLY the JSON encoded

try to do this on your PHP code:

     $arr = array ('item1'=>"test1",'item2'=>"test2",'item3'=>"test3");
     echo json_encode($arr);

and on your Javascript Code do this before just to check:

<script type="text/javascript">
  $(function() {
 $.get("test.php",function(data){
   var obj = $.parseJSON(data);
   alert("Test 1: " + obj.test1);
 });
 </script>

For those who still lost:

I was using "$.post" to send some data and retrieve info. When using that, my JSON return was coming like a string.

Solution: Use the 4th parameter dataType as json.

(Accordingly to http://api.jquery.com/jQuery.post/).

eg.:

$.post('http://SOMEWHERE.COM/A/B/C',
   { 
     parameter:value
   },
   function (data) {
     // success
   },
   'json'
);