[英]Returning a JSON result from a PHP REST web service
我有一個用PHP編寫的REST Web服務,我使用POST請求調用它(為此使用curl)。 Web服務應返回JSON文檔。 問題是,我不確定將此文檔發送回Web服務客戶端的正確方法是什么。 只是回應它就足夠了嗎?
現在,看起來這是我可以讓JSON文檔出現在POST請求結果中的唯一方法($ result變量):
$result = curl_exec($ch);
您可以在Array或Object中格式化結果,然后使用json標頭回顯它。 即
$result_json = array('name' => 'test', 'age' => '16');
// headers for not caching the results
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// headers to tell that result is JSON
header('Content-type: application/json');
// send the result now
echo json_encode($result_json);
希望這有幫助,謝謝
要從php獲取json結果,你應該使用
echo json_encode($result_json)
但是回聲沒有退出程序所以在使用echo之后最好退出程序,但是你可以使用簡寫
exit(json_encode($result_json));
我已經實現了幾次,我只是將它作為字符串發布到WS並從WS回顯作為字符串再次作為響應。 我為此使用了json_encode和json_decode函數...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.