5

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.

Community
  • 1
  • 1
TommyG
  • 4,145
  • 10
  • 42
  • 66
  • 1
    If you make a URL request on iOS with that page address you will basically get the array encoded as json, then you cna decode it into an NSArray on iOS – Daniel Nov 11 '11 at 16:45
  • 1
    Why do you believe that json_encode isn't providing a JSON structure? – Jason McClellan Nov 11 '11 at 16:46
  • 1
    @TommyG this is a JSON structure, it's a JSON array. I suggest you make youself familiar with JSON a bit more - http://www.json.org/ – kgilden Nov 11 '11 at 17:01

1 Answers1

4

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

totallyNotLizards
  • 8,489
  • 9
  • 51
  • 85
  • 2
    JSON doesn't require key=>value pairs. JSON is just JS syntax. In this example, he encoded an array so what he got was JS syntax for an array. If he used an associative array, he'd get JS syntax for an anonymous object, which is what most of us are used to seeing when we think of JSON. – Jason McClellan Nov 11 '11 at 16:58