Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding JSON in PHP to be used in iPhone app

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.

like image 722
TommyG Avatar asked Oct 09 '22 12:10

TommyG


1 Answers

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

like image 70
totallyNotLizards Avatar answered Oct 13 '22 09:10

totallyNotLizards