資料載入中

胡言亂語

在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);

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

https://innstory.com/story-在PHP中通過POST發送JSON-2048

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

下一篇
php定時執行任務ignore_user_abort()函式 
  • 1,335
  • 0
  • 0

發表留言

作者簡介

離不開電腦的宅男


推薦閱讀

作者其他相關類別故事

CSS3濾鏡Filter的十種特效

CSS3濾鏡Filter的十…

Mark Chang 7 年又 233 天 2K

CSS 濾鏡效果 主要是運用在圖片上,以實現一些特效。 grayscal()將網頁上影像轉換成灰階影...

jQuery resize取得瀏覽器目前視窗寬度

jQuery resize取…

Mark Chang 7 年又 206 天 2.7K

在使用CSS調整RWD顯示時~ 也可以使用javascript來做一些輔助,例如判斷目前瀏覽器的...

PHP如何移除 x-powered-by 資訊

PHP如何移除 x-powe…

Mark Chang 4 年又 191 天 1.4K

xpoweredby 主動披露使用程式版本訊息,增加資安風險。 可透過以下方式隱藏 xpowered...