PHP json_encode问题与反斜杠和数组名称 [英] PHP json_encode Problem with Backslash and Array Name
问题描述
我正在将一些postgresql数据转换为PHP json_encode,但存在一些问题:
I'm converting some postgresql data to PHP json_encode, but I have some problems:
-
json_encode向数据中的所有斜杠添加反斜杠.
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...
,而且我不希望将数组放在索引为"0"但名称为"attach:"的对象中
and i don't want my array inside the object named with index "0" but with the name "attach:"
我的JSON输出:
{"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"}]}]}
我的代码:
<?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);
}
?>
谢谢
推荐答案
第一点,如果我尝试这样做:
For the first point, if I try doing this :
$str = "this / string";
var_dump(json_encode($str));
我得到了:
string '"this \/ string"' (length=16)
也有反斜杠.
查看 json.org ,似乎JSON标准定义了在字符串中的斜杠应逃脱.
Looking at json.org, it seems the JSON standard defines that slashes, inside strings, should be escaped.
因此,json_encode()
似乎在做正确的事.
So, json_encode()
seems to be doing the right thing.
如果您不希望这些斜杠被转义,那么您就不需要有效的JSON,并且不应该与json_encode
一起使用.
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 );
相反,您应该使用:
$posts[] = array(..., 'attach' => $posts2 );
这样,数组的最后一个元素将具有"attach"名称.
This way, that last element of the array will have the 'attach' name.
这篇关于PHP json_encode问题与反斜杠和数组名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!