資料載入中

胡言亂語

在PHP中通過POST發送JSON

這回,我遇到需要通過POST請求發送JSON到API。
剛好利用這次的機會紀錄一下:
//API Url
$url = 'API URL';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'username' => 'MyUsername',
'password' => 'MyPassword',
'Data' => $output_value
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);

另外
使用 php 自帶的json_encode函數對數據進行編碼時,中文都會變成 unicode,這會讓整個資料體積變大。
所以,如果使用的 PHP 版本是 5.4 以上的版本,json_encode函數已經新增了一個選項:
JSON_UNESCAPED_UNICODE

使用方式:
json_encode("測試", JSON_UNESCAPED_UNICODE);

只要加上這個選項,中文部分就會維持。
參考連結網址
以上紀錄~

  • POST請求發送JSON到API的實作
  • PHP json_encode函數中文編碼問題
  • 如何在PHP中處理JSON中文
  • 使用PHP發送JSON數據的技巧
  • PHP版本5.4以上的json_encode選項
https://innstory.com/story-在PHP中通過POST發送JSON-2048

上一篇
 利用htaccess隱藏副檔名html和php

下一篇
php定時執行任務ignore_user_abort()函式 

發表留言

  • Max

    這個問題很常見,確實要注意資料體積的影響。選項的使用挺實用的。
    2026-02-26 下午 6 點回覆

作者簡介

離不開電腦的宅男


推薦閱讀

作者其他相關類別故事

PDO PHP - PDOException - Numeric value out of range 1264 Out of range value for column user_ip at row 1

PDO PHP - PDOE…

Mark Chang 5 年又 110 天 1.6K

最近遇到一個問題,一個Mysql的錯誤訊息。 我想要紀錄一個IP資訊,我會先用以下方式擷取用戶端使用...

當域名 DNS 尚未生效時,如何預先設定及測試網站

當域名 DNS 尚未生效時,…

Mark Chang 4 年又 228 天 2.2K

建置一個新的網站或是將網站搬家時 常常會遇到一個問題,就是要將網址指向到新的網站空間,設定完畢但需要...

使用手機將網址分享到 Line時,如何強制使用預設外部瀏覽器開啟?

使用手機將網址分享到 Lin…

Mark Chang 4 年又 83 天 1.7K

如標題,當厭惡了每次在line上面分享demo網址給客戶時點選網址就會使用line的瀏覽器開啟。 ...