How to Convert Data Files in PHP with the Konbert API

Konbert is a file conversion service that offers an API to convert files between various formats like CSV, JSON, Avro, or Arrow. In this article, we will learn how to convert files using PHP with the Konbert API.

How does the Konbert API work?

The Konbert API has a single endpoint, /convert, that accepts file input in various formats and returns output in a specified format. The API requires an API key to authenticate the requests. The endpoint accepts input files via upload, URL, or a string of data. You can specify the input and output formats and set options for the output format.

Example of converting a file using PHP with cURL

Here's an example of converting a JSON file to CSV using the Konbert API with cURL in PHP:

<?php

$apiKey = '<your_api_key>';
$inputFile = '<input_file_path>';
$outputFile = '<output_file_path>';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => 'https://konbert.com/api/v1/convert',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => [
    'input[file]' => new CURLFILE($inputFile),
    'input[format]' => 'json',
    'output[format]' => 'csv',
    'output[options][delimiter]' => ',',
    'sync' => 'true',
  ],
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer ' . $apiKey,
  ],
]);

$response = curl_exec($curl);

if (curl_errno($curl)) {
  echo 'Failed to convert file: ' . curl_error($curl);
  exit;
}

curl_close($curl);

file_put_contents($outputFile, $response);

echo 'File converted successfully';

In this example, we're using the cURL library to make the HTTP request. We're setting the API key as an HTTP header and specifying the input file using the CURLFILE object. We're also specifying the input format as JSON and the output format as CSV. We've set the output delimiter to , to separate the values in the CSV file.

We're checking if there's any error in the HTTP request using curl_errno, and if there isn't, we're writing the response to the output file using file_put_contents.

Conclusion

Converting files between different formats is an important task in data processing. With the Konbert API, you can easily convert files between various formats like CSV, JSON, Avro, or Arrow. In this article, we've learned how to convert files using PHP with the Konbert API.