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
?>
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);
$var = "hel\"lo";
$var2 = "hel\nlo";
echo json_encode(array($var, $var2));
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
json_encode and json_decode should do the trick.
http://php.net/manual/en/function.json-encode.php
You can use this: Json - encode a PHP function
精彩评论