Example of PHP Method for Sending JSON Format Strings Based on CURL
- 2021-09-12 00:37:21
- OfStack
This article illustrates how PHP sends JSON format strings based on CURL. Share it for your reference, as follows:
/*
* post Send JSON Format data
* @param $url string URL
* @param $data_string string Specific content of the request
* @return array
* code Status code
* result Return results
*/
function post_json_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array('code'=>$return_code, 'result'=>$return_content);
}
$arr = array('a'=>'555','b'=>56454564);
dump(post_json_data('http://192.168.211.1/html/dump.php',json_encode($arr)));
Note: When receiving data, it is not used
$_POST
, but
$content = file_get_contents('php://input');
PS: Here we recommend several practical json online tools for your reference:
Online JSON code verification, verification, beautification and formatting tools:
http://tools.ofstack.com/code/json
JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat
Online XML/JSON Interconversion Tool:
http://tools.ofstack.com/code/xmljson
json code online formatting/beautification/compression/editing/conversion tool:
http://tools.ofstack.com/code/jsoncodeformat
C Language Style/HTML/CSS/json Code Formatting and Beautification Tool:
http://tools.ofstack.com/code/ccode_html_css_json
For more readers interested in PHP related content, please check the topics on this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Operation and Operator Usage Summary" and "php Common Database Operation Skills Summary"
I hope this article is helpful to everyone's PHP programming.