Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Monday, January 29, 2018

How to Send and Receive JSON Data with PHP using cURL?

cURL is a tool to transfer data from server to client or vice versa. There are many protocols used by cURL such that FILE, FTP, HTTPS, POP3, SMTP, TELNET etc. 









Following steps requires  to send JSON data via post request with PHP cURL:
Step-1: First we will specify URL ($url) where the JSON data need to be send.
Step-2: Initiate cURL resource using curl_init().
step-3: Encode PHP array data into a JSON string using json_encode().
step-4: Attach JSON data to the POST field using the CURLOPT_POSTFIELDS option.
step-5:  Set header option to Content-Type: application/json
step-6: Return response as string CURL_RETURNTRANSFER option
Step-7: Finally curl_exec() function is used to execute the POST request api url.

index.php
In the following example code, We will pass POST data on API URL as JSON format.
<?php
$id='007xy2';
$name="Durga Prasad Padhan";
$address="Bargarh";
$phone=9938216146;
//API URL
$url="http://localhost/curl/example.php";
$data =array("Voter ID" =>$id,"Name" =>$name,"Address" =>$address,"Phone"=>$phone);
$newData = curl_init( $url );
# Setup request to send json via POST.
$person = json_encode( array( "Person"=> $data ) );
curl_setopt( $newData, CURLOPT_POSTFIELDS, $person );
curl_setopt($newData, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $newData, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $newData, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($newData);
curl_close($newData);
# Print response.
echo "<pre>" . $result. "</pre>";
?>
example.php
In the following code, We will Receive JSON POST data using PHP.
1st: jsone_decode() function is used to decode JSON data into array format .
2nd: file_get_content() function is used to receivedata in readable format.
<?php
header("Content-Type:application/json");
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
?>
Output:

How To Convert PHP Array To CSV File And Download Automatically.

The function convert_array_to_csv($input_array, $download_file_name, $delimiter)  have 3 parameters which is used in below example.
The first parameter is used to convert PHP array to  CSV and The other two parameters are used to specify the name of the CSV file, and a delimiter.In this example we are using some function i.e. fopen(), fputcsv(), fseek() and fpassthru().

fopen() : This function opens a file or URL.
fopen() takes two parameters
1.php://memory is  read-write streams that allow temporary data to be stored in a file. php://memory will always store its data in memory.
2. Mode of the file i.e  "w" (Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist).

fputcsv():This is used for formatting a line as CSV and writes it to an   open file.

fseek():This function moves the file pointer from its current  position to a new position, forward or backward, specified by the number of    bytes.

After executing fseek() in this example  CSV is ready to download. In order to   download/Export the file, We use

header('Content-Type: application/csv');
header('Content-Disposition: attachement; 
                        filename="' $download_file_name'";');

This  function tells the browser how to interpret it  content and also it tells the  browser that we want to download not display the content of the file.

fpassthru():This function reads all data from the current position in  an open file, until EOF, and writes the result to the output buffer.

index.php

<?php
function convert_array_to_csv($input_array, $download_file_name, $delimiter)
{
  $f = fopen('php://memory', 'w'); /* it will store its data in memory */

  
foreach ($input_array as $line) {

  fputcsv($f, $line, $delimiter); 

   }
 fseek($f, 0);   

 /* modify header to be downloadable csv file */
 header('Content-Type: application/csv');
 header('Content-Disposition: attachement; filename="' . $     download_file_name. '";');

 fpassthru($f); /* Send file to browser for download */
}

/** Array to convert to csv */
$array = Array(
    Array('RollNo',
         'FirstName', 
        'LastName'
    ),
    Array(1,
        'Durga',
        'prasad'
    ),
    Array(2,
        'Ranjan',
        'Kumar'
    ),
    Array(3,
        'Suresh',
        'Sarika'
    )
);
convert_array_to_csv($array, 'report.csv', ',');
?>  

Finally after executing index.php a CSV file name report.csv
automatically downloaded. And when we open this file in
Notepad it looks like this

RollNo,FirstName,LastName
1,Durga,prasad
2,Ranjan,Kumar
3,Suresh,Sarika

More Posts

FOLLOW