我创建了一个API,它将A数据字符串发送到远程API并获得响应。我发送的数据字符串是
$data_string = '{"listings":[{"title":"B","city":"xyz","available_date":"2013-06-25 00:00:00"}]}';
$datas = http_build_query(json_decode($data_string,true));
然后我使用curl请求发送了这个$datas
字符串,得到了以下响应:
{:response=>[{:status=>"error", :errors=>"You already have a entry with this city", :data=>{"title"=>"B","status"=>"STATUS_ACTIVE", "created_by"=>"import", "available_type"=>"Date", "source"=>"API"}}]}
现在我无法将此响应转换为数组。
答案 0 :(得分:1)
我假设您无法控制响应。如果这样做,您应该在发送之前将其变为有效的JSON。
假设您无法控制响应,则需要将其转换为JSON,因为这是尝试(和失败)的原因。然后你可以解析它。
尝试这样的事情:
$response = '{:response=>[{:status=>"error", :errors=>"You already have a entry with this city", :data=>{"title"=>"B","status"=>"STATUS_ACTIVE", "created_by"=>"import", "available_type"=>"Date", "available_date"=>Mon, 19 Aug 2013, "source"=>"API"}}]}';
$response= preg_replace(array('/=>([^"]+?)(, ?"|\})/', '/[": ]*([^:="]+)"?=>/', '/", "/'), array('=>"$1"$2', '"$1":', '","'), $response);
$response = json_decode($response);
var_dump($response);
执行以下操作:
"
,:
或空格开头的所有内容,然后是字符串后跟=>
,并带有字符串的引用版本。因此,:status=>
变为"status":
。我们同时删除元素之间的额外空格。这使它成为合适的JSON。json_decode()
解析JSON。Voila,你有一个包含你数据的对象,如下所示:
object(stdClass)#1 (1) {
["response"]=>
array(1) {
[0]=>
object(stdClass)#2 (3) {
["status"]=>
string(5) "error"
["errors"]=>
string(39) "You already have a entry with this city"
["data"]=>
object(stdClass)#3 (6) {
["title"]=>
string(1) "B"
["status"]=>
string(13) "STATUS_ACTIVE"
["created_by"]=>
string(6) "import"
["available_type"]=>
string(4) "Date"
["available_date"]=>
string(16) "Mon, 19 Aug 2013"
["source"]=>
string(3) "API"
}
}
}
}
您可以使用例如$response->response[0]->errors
。
答案 1 :(得分:0)
我认为你可以这样做:
$str = '{:response=>[{:status=>"error", :errors=>"You already have a entry with this city", :data=>{"title"=>"B","status"=>"STATUS_ACTIVE", "created_by"=>"import", "available_type"=>"Date", "source"=>"API"}}]}';
$str = str_replace(":", "", $str);
$str = str_replace("=>", ":", $str);
$str = str_replace(array("\n","\r"),"",$str);
$str = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$str);
$str = (array)json_decode($str);
print_r($str);
答案 2 :(得分:-2)
我建议不要使用此
$datas = http_build_query(json_decode($data_string,true));
保持这个:
echo $data_string;
从api调用返回响应执行以下操作:
$data = json_decode('Your cURL response'); // this becomes an object.
我已经构建了一个api,你可以使用这个https://github.com/busfirms/api