Saturday, July 17, 2010

Transfer JSON encoded files in PHP with CURL

CLIENT (makes request)
  • How do we transform a PHP object into JSON?
          $doc = json_encode($request) -> returns a string containing the JSON representation of $request.
  • How do we use the POST method to reach a page in a different server (plus there is no form in the file that builds the Json file)?
          We use CURL to transfer the file using POST (POST is defined in the options)

          curl_setopt($curl_handle, CURLOPT_POST, TRUE);

          curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $doc);
  • How do we get the response that the server returns (saying if the request was successful)
          When we execute the transfer with cURL we get a response:

            $buffer = curl_exec($curl_handle);

           $response = json_decode($buffer);
  • Why is the response a JSON doc? --> Because that’s how the server built it
  • Steps:
  1. Create the object (associative array) in PHP
  2. Encode it into a JSON document:   $doc = json_encode($request);
  3. Transmit it using cURL:                 $buffer = curl_exec($curl_handle);

SERVER (processes the request, returns response)
  • Since we don’t have the $_SERVER variable, how do we get the file that is being transferred by cURL?
           We use $doc = file_get_contents(‘php://input’)
    • php://input allows you to read raw POST data
    • file_get_contents reads an entire file into a string
  • How do transform the string into something that we can process with PHP?
    • json_decode($doc) takes a JSON encoded string and converts it into a PHP variable
    • How do we transmit the response:
      • echo json_encode($response);

    No comments:

    Post a Comment