Frank
Frank

Reputation: 455

escape strings correctly into JSON data in PHP

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
?>

Upvotes: 1

Views: 3095

Answers (5)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

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

Upvotes: 3

YonoRan
YonoRan

Reputation: 1728

You can use this: Json - encode a PHP function

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

$var = "hel\"lo";
$var2 = "hel\nlo";
echo json_encode(array($var, $var2));

Upvotes: 3

djdy
djdy

Reputation: 6919

json_encode and json_decode should do the trick.

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

Upvotes: 2

Quentin
Quentin

Reputation: 943214

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);

Upvotes: 7

Related Questions