I know that this is really basic, but I looked everywhere and I cant find the right answer.
With reference to a previous question of mine: How to format list in PHP to be used as an NSArray in Objective C?
I have been trying to write a short PHP script (knowing nothing about it) that my iphone app will call in order to get a list of items. I thought about just using ECHO, since I REALLY dont need to send more than one array of items, but was advised to use JSON or XML, so chose JSON.
I am looking for a way to encode the array to JSON and the only thing I could find was json_encode which doesnt seem to provide a JSON structure. Here is my PHP code:
<?php
$arr = array ('a', 'b','c','d','e');
echo json_encode($arr);
?>
Is this what I am supposed to use? Am I doing anything wrong? Thanks a lot.
EDIT:
Thats the output when running this PHP script in Terminal:
["a","b","c","d","e"]
As far as I know this is not a JSON structure, but again, i know barely nothing about it.
That's correct as far as I know.
A good way to test whether or not your JSON is valid is to use http://jsonlint.com/
To elaborate:
$arr = array ('a'=>'a value', 'b'=>'b value','c'=>'c value');
echo json_encode($arr);
$arr = array ('a', 'b','c');
echo json_encode($arr);
Should give you:
{"a":"a value","b":"b value","c":"c value"}
["a","b","c"]
As pointed out by @Jason McClellan, the second is correct also.
So, yes you are doing the right thing to encode an array to something readable by javascript.
The other function is json_decode($json);
which obviously decodes json.
Documentation here: http://php.net/manual/en/function.json-encode.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With