2013-02-15 75 views
0

我试图以json格式获得正确的输出,但是我的输出下面有点乱。它应该是这样的: "{"table":"users","operation":"select","username":"inan"}"阵列打印为json,数组和xml

我该如何解决我的问题?

由于

server.php

print_r($_POST); 

client.php

$data = array('table'=>'users', 'operation'=>'select', 'uid'=>'yoyo'); 
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $data); 
$output = curl_exec($curl_handle); 

if ($this->request_response_type == 'array') 
{ 
echo $output; 
} 
else if ($this->request_response_type == 'json') 
{ 
echo json_encode($output); 
} 
else if ($this->request_response_type == 'xml') 
{ 
    //xml conversion will be done here later. not ready yet. 
} 

输出:

"Array\n(\n [table] => users\n [operation] => select\n [uid] => yoyo\n)\n" 
+0

你显示的输出是一个php数组的print_r。如果你想要json,请仔细检查'$ this-> request_response_type'是否返回'json',并记住它是区分大小写的,所以'Json'!='json'。 – 2013-02-15 18:05:57

回答

2

的print_r打印出的阵列不能被解析回一个变量。

在你的server.php中做echo json_encode($_POST);。 然后在你的client.php

<?php 
//... 
$output = curl_exec($curl_handle); 

// and now you can output it however you like 
if ($this->request_response_type == 'array') 
{ 
    //though i don't see why you would want that as output is now useless if someone ought to be using the variable 
    $outputVar = json_decode($output); // that parses the string into the variable 
    print_r((array)$outputVar); 
    // or even better use serialize() 
    echo serialize($outputVar); 
} 
else if ($this->request_response_type == 'json') 
{ 
    echo $output; //this outputs the original json 
} 
else if ($this->request_response_type == 'xml') 
{ 
    // do your xml magic with $outputVar which is a variable and not a string 
    //xml conversion will be done here later. not ready yet. 
} 
-1

看一看成JSON.stringify

+0

如果他在JavaScript中转换数组,是的。他虽然在问关于PHP。 – 2013-02-15 18:06:45

+0

我的坏><感谢澄清。 – aug 2013-02-15 23:44:32