PHP JSON encoding for use in iPhone application

I know this is really thorough, but I searched everywhere, and I can’t find the right answer.

As for the previous question: How to format a list in PHP to be used as an NSArray in Objective-C?

I am trying to write a short PHP script (without knowing anything about it) that my iphone application will call to get a list of elements. I was thinking about using ECHO, since I really do not need to send more than one array of elements, but it was recommended to use JSON or XML, so I chose JSON.

I am looking for a way to encode an array in JSON, and the only thing I could find was json_encode, which does not seem to create a JSON structure. Here is my PHP code:

<?php 

$arr = array ('a', 'b','c','d','e');
echo json_encode($arr);

 ?> 

Is that what I should use? Am I doing something wrong? Many thanks.

EDIT:

This is the output when running this PHP script in the terminal:

["a", "b", "c", "g", "e"]

As far as I know, this is not a JSON structure, but then again, I don't know anything about it.

+5
source share
1 answer

Right, as far as I know.

A good way to check if your JSON is valid is to use http://jsonlint.com/

Develop:

$arr = array ('a'=>'a value', 'b'=>'b value','c'=>'c value');
echo json_encode($arr);
$arr = array ('a', 'b','c');
echo json_encode($arr);

Must give you:

{"a":"a value","b":"b value","c":"c value"}
["a","b","c"] 

As pointed out by @Jason McClellan, the second is also correct.

So yes, you are doing the right thing to encode the array into something readable by javascript.

json_decode($json);, , , json. : http://php.net/manual/en/function.json-encode.php

+4

All Articles