如何使用Curl 和PHP 傳遞JSON 資料以進行PUT、POST、GET 和DELETE
利用Curl 和PHP 進行CRCR是一種便捷的方法。雖然命令列提供了傳遞 JSON 資料的簡單方法,但 PHP 需要自訂實作。
PUT 的PHP Curl 實作:
<?php $data = array('username' => 'dog', 'password' => 'tall'); $data_json = json_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_json))); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
PHP Curl POST 的實作:PHP Curl實作GET(替代方法):
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
刪除的 PHP Curl 實作:
<?php $query_string = http_build_query($data); $url = $url . '?' . $query_string; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ?>
以上是如何使用Curl和PHP發送JSON資料進行REST API CRUD操作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!