PHP json_encode Problem with Backslash and Array Name

json, pdo, php, postgresql

Solution

For the first point, if I try doing this :

$str = "this / string";
var_dump(json_encode($str));

I get :

string '"this \/ string"' (length=16)

With backslashes too.

Looking at json.org, it seems the JSON standard defines that slashes, inside strings, should be escaped.

So, `json_encode()` seems to be doing the right thing.

If you do not want those slashes to be escaped, then, you don't want valid-JSON, and should not work with `json_encode`.

For the second point, now, you should not use this :

$posts[] = array(..., $posts2 );

Instead, you should use :

$posts[] = array(..., 'attach' => $posts2 );

This way, that last element of the array will have the 'attach' name.

Problem

I'm converting some postgresql data to PHP json_encode, but I have some problems: json_encode adds an BackSlash to all slashes that I have in my data. In descriptions apears the close of paragraph tag , i think because the backslashes problem... and i don't want my array inside the object named with index "0" but with the name "attach:" MY JSON OUTPUT: ``` {"arns":[{"arn":"CSC-ECN-NAUB109","problem":"description problem<\/p>", "solution":"solution description<\/p>", "0":[{"name":"jquery.png","path":"http:\/\/arn.test.pt\/uploads\/CSC-ECN-NAUB109\/jquery.png"}]}]} ``` MY CODE: ``` <?php require('includes/connection.php'); $modelos_info = (isset($_GET['models'])) ? $_GET['models'] : "none"; if($modelos_info != "none"){ $sth = $dbh->query("SELECT * FROM arn_info JOIN upload2 ON (arn_info.arn=upload2.id_arn) WHERE modelos LIKE '$modelos_info ;%' OR modelos LIKE '%; $modelos_info ;%' "); $sth->setFetchMode(PDO::FETCH_ASSOC); $response = array(); $posts = array(); while($row = $sth->fetch()) { $arn=$row ['arn']; $problem=$row['problem']; $solution=$row['solution']; $name=$row['name']; $path=$row['path']; $posts_anexos['attach'] = $posts2; $posts2[] = array('name'=> $name , 'path'=> 'http://arn.test.pt/' .$path); $posts[] = array('arn'=> $arn , 'problem'=> $problem , 'solution'=> $solution, $posts2 ); } $response['arns'] = $posts; $fp = fopen('arns.json', 'w'); fwrite($fp, json_encode($response)); fclose($fp); echo json_encode($response); } ?> ``` Thanks

Original source