Using phpcurl to send json data is the same as other data in curlpost. next I will summarize several examples of sending json data in curlpost, hoping to deepen your understanding of curlp
Using php curl to send json data is the same as other data in curl post. next I will summarize several examples of sending json data in curl post, I hope you can better understand the curl post json data.
Example 1 code:
- $ Data = array ("name" => "Hagrid", "age" => "36 ");
- $ Data_string = json_encode ($ data );
-
- $ Ch = curl_init ('http: // api. local/rest/users ');
- Curl_setopt ($ ch, CURLOPT_CUSTOMREQUEST, "POST ");
- Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data_string );
- Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
- Curl_setopt ($ ch, CURLOPT_HTTPHEADER, array (
- 'Content-Type: application/json ',
- 'Content-Length: '. strlen ($ data_string ))
- );
-
- $ Result = curl_exec ($ ch );
Example 2: The code is as follows:
- Function http_post_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 ($ return_code, $ return_content );
- }
- $ Url = "http://xx.xx.cn ";
- $ Data = json_encode (array ('a' => 1, 'B' => 2 ));
- List ($ return_code, $ return_content) = http_post_data ($ url, $ data );
Example 3 code:
- $ Data = '{
- "Button ":[
- {
- "Type": "click ",
- "Name": "Today's songs ",
- "Key": "V1001_TODAY_MUSIC"
- },
- {
- "Type": "click ",
- "Name": "Introduction to singers ",
- "Key": "V1001_TODAY_SINGER"
- },
- {
- "Name": "menu ",
- "Sub_button ":[
- {
- "Type": "click ",
- "Name": "hello word ",
- "Key": "V1001_HELLO_WORLD"
- },
- {
- "Type": "click ",
- "Name": "Like Us ",
- "Key": "V1001_GOOD"
- }]
- }]
- }';
- $ Ch = curl_init ($ urlcon); // request URL
- Curl_setopt ($ ch, CURLOPT_CUSTOMREQUEST, "POST ");
- Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data); // $ data JSON string
- Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
- Curl_setopt ($ ch, CURLOPT_HTTPHEADER, array ('content-Type: application/json', 'Content-Length: '. strlen ($ data )));
- $ Data = curl_exec ($ ch );
- Print_r ($ data); // returned after successful creation: {"errcode": 0, "errmsg": "OK "}
Summary: the core code is Content-Type: application/json. this is the file format Type.