在PHP中,正则表达式是从下面提取“采取”的,考虑到它是动态的并始终处于状态之后:
HTTP/1.0 200 OK
Date: Sat, 09 Feb 2013 23:07:09 GMT
Accept-Ranges: bytes
Server: Noelios-Restlet-Engine/1.1.7
Content-Type: application/json;charset=UTF-8
Content-Length: 147
X-Cache: MISS from geonisis-2.eurodns.com
X-Cache-Lookup: MISS from geonisis-2.eurodns.com:80
Via: 1.0 geonisis-2.eurodns.com (squid/3.1.10)
Connection: keep-alive
{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}
以下显示我应该使用json解码。如何实现这一目标?
以上生成使用:
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
答案 0 :(得分:3)
通过更改以下内容从响应中删除标头:
curl_setopt($process, CURLOPT_HEADER, false);
然后使用:
解码JSON字符串$data = json_decode($curlResponse, true);
答案 1 :(得分:2)
如果您从响应中丢弃标头,则可以使用:
$json = '{"service":"availability","domain":"","timestamp":1360451229,
"content":{"domainList":[{"status":"taken","name":""}]}}';
$data = json_decode($json, TRUE);
echo $data['content']['domainList'][0]['status'];
答案 2 :(得分:1)
为什么要关心标题?这是一个JSON字符串,只需解码它就可以轻松访问
在php中:
$jsonobj = json_decode('{"service":"availability","domain":"","timestamp":1360451229, "content":{"domainList":[{"status":"taken","name":""}]}}');
在javascript中:
var jsonobj = JSON.parse('{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}');
答案 3 :(得分:1)
$string = '
HTTP/1.0 200 OK
Date: Sat, 09 Feb 2013 23:07:09 GMT
Accept-Ranges: bytes
Server: Noelios-Restlet-Engine/1.1.7
Content-Type: application/json;charset=UTF-8
Content-Length: 147
X-Cache: MISS from geonisis-2.eurodns.com
X-Cache-Lookup: MISS from geonisis-2.eurodns.com:80
Via: 1.0 geonisis-2.eurodns.com (squid/3.1.10)
Connection: keep-alive
{"service":"availability","domain":"","timestamp":1360451229,"content":{"domainList":[{"status":"taken","name":""}]}}';
$parts = explode("\n", $string);
$json = end($parts);
$data = json_decode($json);
$status = $data->content->domainList[0]->status; die;
echo $status;
编辑(基于问题更新):
从cURL请求中删除CURLOPT_HEADER行。这将简化响应并使其更容易解析。
答案 4 :(得分:0)
如果您需要使用标题,则有两种选择;
// first: regex
preg_match('~"status":"(.*?)"~i', $return, $match);
// print_r($match);
echo $match[1]; // taken
// second: json encode
$response = explode("\r\n\r\n", $return, 3);
// print_r($response);
$json_object = json_decode($response[2]);
$json_array = json_decode($response[2], true); // toArray
// echo $json_object->content->domainList[0]->status;
echo $json_array['content']['domainList'][0]['status'];