簡體   English   中英

通過POST PHP發送JSON數據的正確方法

[英]Correct way to send JSON DATA via POST php

通過CURL發送$json數據的正確方法是嗎? 在PHP中,

我在一個PHP中有$json數據,我可以使用CURL通過POST通過POST將數據信息發送到我的api ,?

你有一些例子,非常感謝!

是。 你可以做。

例如。

// $json_string : Your json String
    $ch = curl_init('http://api.example.com/post');                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_string);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($json_string))                                                                       
    );                                                                                                                   

    $result = curl_exec($ch);

請在發帖前找到:
http://bavotasan.com/2011/post-url-using-curl-php/

在$ data的某個鍵中,放入$ json。

function post_to_url($url, $data) {
   $fields = '';
   foreach($data as $key => $value) { 
      $fields .= $key . '=' . $value . '&'; 
   }
   rtrim($fields, '&');

   $post = curl_init();

   curl_setopt($post, CURLOPT_URL, $url);
   curl_setopt($post, CURLOPT_POST, count($data));
   curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
   curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);

   $result = curl_exec($post);

   curl_close($post);
}

    $json = json_encode($your_json); //Your json data
$data = array(
   "name" => "c.bavota",
   "website" => "http://bavotasan.com",
   "twitterID" => "bavotasan",
       "json" => $json
);

post_to_url("http://yoursite.com/post-to-page.php", $data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM