다음 페이지가 있습니다.PHP의 cURL을 통한 JSON이 작동하지 않습니다.
페이지 json.php
:
$json_data = array(
'first_name' => 'John',
'last_name' => 'Doe',
'birthdate' => '12/02/1977',
'files' => array(
array(
'name' => 'file1.zip',
'status' => 'good'
),
array(
'name' => 'file2.zip',
'status' => 'good'
)
)
);
$url = 'http://localhost/test.php';
$content = json_encode($json_data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
"Content-type: application/json",
"Content-Length: " . strlen($content)
)
);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content));
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT);
curl_close($curl);
echo $header_sent;
echo '<br>';
echo $status;
echo '<br>';
echo $json_response;
페이지 test.php
:
echo '<pre>';
print_r($_POST);
echo '</pre>';
, 나는 다음과 같은 결과를 얻을 :
POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150
200
Array
(
)
왜 보내려는 POST 문자열을 볼 수 없습니까?
편집 :
내가 (@의 landons의 의견에 따라)을 Content-type: application/json
헤더를 설정하지 않은 경우, 나는 다음과 같은 결과를 얻을 :
POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded
200
Array
(
[json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name":
)
가
application/json Content-type 헤더를 보내지 않으면 어떻게 될까요? – landons
@landons 문자열이 잘립니다. (내 업데이트를 참조하십시오.) – Alex
멀티 파트가 아닌 비 URL 인코딩 된 내용에'$ _POST' 배열을 사용하지 마십시오. 'var_dump (file_get_contents ('php : // input'));' – Wrikken