1

I have some rather long string containing just about anything that I want to convert to JSON from PHP. Is there a simple way to do this? For example I would like this JSON ouput to work:

<?php
   $var = "hel\"lo";
   $var2 = "hel\nlo";
   echo "[\"".$var."\", \"".$var2."\"]"; // should give me the data: hel"lo and hel<new line>lo
?>
3
  • In case the answers didn't make it clear enough, use json_encode() Commented Jun 27, 2011 at 13:17
  • 1
    @Wesley why do you feel the need to re-post all the 5 correct answers as a comment? Commented Jun 27, 2011 at 13:22
  • @Matthieu: I didn't see the need for the 6th answer, so I just left a comment to enforce the others. Commented Jun 27, 2011 at 13:27

5 Answers 5

7

Construct a PHP data structure and then run it through json_encode. Don't try to build JSON by mashing together strings.

$foo = array($var, $var2);
echo json_encode($foo);
Sign up to request clarification or add additional context in comments.

1 Comment

@Salman A — Not properly. It outputs a string. Since the top level data type in JSON must be an array or an object, it should throw an exception instead of outputting anything. That is beside the point though, the question is about an array.
3
$var = "hel\"lo";
$var2 = "hel\nlo";
echo json_encode(array($var, $var2));

Comments

3

You could use json_encode (EDIT - i changed the array so that when encoded the output is what was requested)

var $json = array('hello','hello');

echo (json_encode($json));

look here for reference.

EDIT - to use json_encode you must have php vesion > 5.20 . if you need an alternative you can use the zend_framework component Zend_JSON

4 Comments

The target is an array, not an object, that => should be a ,.
@Quentin => is a language construct for arrays, not objects. This enables to specify on the left the array key, and on the right the array value. You can then do : $value = $myarray['hello'];. However, the OP seems to want array('hello', 'hello') anyway.
It0s an associative array, as key -> value so you have a json object with a property named hello with a value of hello, but yes, the question asked for what you wrote! :)
@Matthieu — It is a language construct for PHP associative arrays which map onto JSON objects. Numerically indexed arrays (which map onto JSON arrays) are created with a simple list of values and no explicit keys. The example in the question makes it clear that a JSON array is desired.
2

json_encode and json_decode should do the trick.

http://php.net/manual/en/function.json-encode.php

Comments

1

You can use this: Json - encode a PHP function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.