Loading...

在PHP中通過POST發送JSON

Temperature: 0 °C

Mark ChangMark Chang
author_tools

這回,我遇到需要通過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);

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

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

Prev
 利用htaccess隱藏副檔名html和php

Next
php定時執行任務ignoreuserabort_函式 

About the Author

Mark Chang

離不開電腦的宅男

Visitor message

Leave some footprints to prove that you visited me

Recommended reading

Author's other related stories

使用jQuery阻止input直接按Enter就送出表單

使用jQuery阻止inpu...

使用表單是傳送資料裡經常會用到的方式。 這時當使用者輸入表單後習慣上按下Enter,則會將表單內容送...

使用 Closure Compiler 幫 javascript 瘦身

使用 Closure Com...

JavaScript(縮寫為JS)是一種進階的、直譯的程式語言,且作為客戶端手稿語言在使用者的瀏覽器...

PHP–implode() 將陣列轉成字串

PHP–implode() ...

pexelsphoto 使用implode將陣列轉換成字串; $ar=array(&#;a&#;,&...

Please select an option

error

Hi, thank you for your participation, but you cannot vote repeatedly~

Join innstory now and start recording your story.

"Innstory" is a place to store stories. We are committed to becoming a warm platform. Deepening the bonds between people is our direction.
We are convinced that the blockchain between people is not just a cold calculation. Join us now.

Wrong format