Receive JSON POST with PHP

前端 未结 7 2520
Happy的楠姐
Happy的楠姐 2020-11-21 04:42

I’m trying to receive a JSON POST on a payment interface website, but I can’t decode it.

When I print :

echo $_POST;

I get:

7条回答
  •  轮回少年
    2020-11-21 05:26

    I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.

    // import mpdf somewhere
    require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';
    
    // get mpdf instance
    $mpdf = new \Mpdf\Mpdf();
    
    // src php file
    $mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
    // where we want to save the pdf
    $mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';
    
    // encode $_POST data to json
    $json = json_encode($_POST);
    
    // init curl > pass the url of the php file we want to pass 
    // data to and then print out to pdf
    $ch = curl_init($mysrcfile);
    
    // tell not to echo the results
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );
    
    // set the proper headers
    curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);
    
    // pass the json data to $mysrcfile
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    
    // exec curl and save results
    $html = curl_exec($ch);
    
    curl_close($ch);
    
    // parse html and then save to a pdf file
    $mpdf->WriteHTML($html);
    $this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);
    

    In $mysrcfile I'll read json data like this (as stated on previous answers):

    $data = json_decode(file_get_contents('php://input'));
    // (then process it and build the page source)
    

提交回复
热议问题