Skip to content

Commit 3750783

Browse files
committed
Conversion Tools API PHP Client
1 parent ddcb9e3 commit 3750783

9 files changed

Lines changed: 409 additions & 0 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
vendor/

README.md

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# [Conversion Tools](https://conversiontools.io) API PHP Client
2+
3+
[Conversion Tools](https://conversiontools.io) is an online service that offers a fast and easy way to convert documents between different formats, like XML, Excel, PDF, Word, Text, CSV and others.
4+
5+
This client allows to integrate the conversion of the files into PHP applications.
6+
7+
To convert the files PHP Client uses the public [Conversion Tools REST API](https://conversiontools.io/api-documentation).
8+
9+
## Installation
10+
11+
### Installation using Composer
12+
13+
```bash
14+
composer require conversiontools/conversiontools-php
15+
```
16+
17+
or without composer:
18+
19+
```php
20+
require_once('conversiontools-php/src/autoload.php');
21+
```
22+
23+
## Examples
24+
25+
To use REST API - get API Token from the Profile page at https://conversiontools.io/profile.
26+
27+
See example `test.php` in the `./examples/` folder.
28+
29+
```php
30+
<?php
31+
32+
require_once __DIR__ . '/vendor/autoload.php';
33+
34+
use \ConversionTools\ConversionClient;
35+
36+
// put token here from your Profile page at https://conversiontools.io/profile
37+
$token = '';
38+
39+
$fileInput = 'test.xml';
40+
$fileOutput = 'test.csv';
41+
$options = ['delimiter' => 'tabulation'];
42+
43+
$client = new ConversionClient($token);
44+
try {
45+
$client->convert('convert.xml_to_csv', $fileInput, $fileOutput, $options);
46+
} catch (Exception $e) {
47+
print 'Exception: ' . $e->getMessage() . "\n";
48+
}
49+
```
50+
51+
## API
52+
53+
### Create `ConversionClient` instance with a token.
54+
```php
55+
use \ConversionTools\ConversionClient;
56+
57+
$client = new ConversionClient('<token>');
58+
```
59+
60+
Where `<token>` is API token from the account's Profile page https://conversiontools.io/profile.
61+
62+
### Convert input file and download the result
63+
```php
64+
$client = new ConversionClient($token);
65+
try {
66+
$client->convert('<conversion type>', $fileInput, $fileOutput, $options);
67+
} catch (Exception $e) {
68+
print 'Exception: ' . $e->getMessage() . "\n";
69+
}
70+
```
71+
72+
Where
73+
- `<conversion type>` is a specific type of conversion, from [API Documentation](https://conversiontools.io/api-documentation).
74+
- `$fileInput` is the filename of the input file
75+
- `$fileOutput` is the filename of the output file
76+
- `$options` is a PHP array with options for a corresponding converter, for example:
77+
```php
78+
$options = ['delimiter' => 'tabulation'];
79+
```
80+
81+
## Requirements
82+
83+
PHP version 5.4.0 or later.
84+
85+
## Documentation
86+
87+
List of available Conversion Types and corresponding conversion options can be found on the [Conversion Tools API Documentation](https://conversiontools.io/api-documentation) page.
88+
89+
## License
90+
91+
Licensed under [MIT](./LICENSE).
92+
93+
Copyright (c) 2020 [Conversion Tools](https://conversiontools.io)

composer.json

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"name": "conversiontools/conversiontools-php",
3+
"type": "library",
4+
"description": "Conversion Tools REST API PHP Client library",
5+
"keywords": ["convert","conversion","conversiontools","convert files","client","api","sdk"],
6+
"homepage": "https://github.com/conversiontools/conversiontools-php",
7+
"license": "MIT",
8+
"require": {
9+
"ext-curl": "*",
10+
"ext-json": "*",
11+
"php": ">=5.4.0"
12+
},
13+
"config": {
14+
"bin-dir": "bin"
15+
},
16+
"autoload": {
17+
"psr-4": {
18+
"ConversionTools\\": "src/"
19+
}
20+
},
21+
"authors": [
22+
{
23+
"name": "Conversion Tools",
24+
"homepage": "https://conversiontools.io"
25+
}
26+
]
27+
}

composer.lock

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/test.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
require_once __DIR__ . '/vendor/autoload.php';
4+
5+
use \ConversionTools\ConversionClient;
6+
7+
// put token here from your Profile page at https://conversiontools.io/profile
8+
$token = '';
9+
10+
$fileInput = 'test.xml';
11+
$fileOutput = 'test.csv';
12+
13+
$options = ['delimiter' => 'tabulation'];
14+
15+
$client = new ConversionClient($token);
16+
try {
17+
$client->convert('convert.xml_to_csv', $fileInput, $fileOutput, $options);
18+
} catch (Exception $e) {
19+
print 'Exception: ' . $e->getMessage() . "\n";
20+
}

src/API.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
namespace ConversionTools;
4+
5+
class API
6+
{
7+
public static function createTask($type, $file_id, $options = [])
8+
{
9+
$data = [
10+
'type' => $type,
11+
'options' => array_merge(['file_id' => $file_id], $options)
12+
];
13+
$result = Request::requestAPI('POST', ConversionClient::$baseUrl . '/tasks', json_encode($data));
14+
$json = json_decode($result, true);
15+
if ($json['error'] !== NULL) {
16+
throw new \Exception('Conversion Error: ' . $json['error']);
17+
}
18+
return $json['task_id'];
19+
}
20+
21+
public static function getTaskStatus($task_id)
22+
{
23+
$result = Request::requestAPI('GET', ConversionClient::$baseUrl . "/tasks/$task_id");
24+
$json = json_decode($result, true);
25+
if ($json['error'] !== NULL) {
26+
throw new \Exception('Conversion Error: ' . $json['error']);
27+
}
28+
return [$json['status'], $json['file_id']];
29+
}
30+
31+
public static function uploadFile($filename)
32+
{
33+
if (is_readable($filename) !== TRUE) {
34+
throw new \Exception('Cannot read input file');
35+
}
36+
$result = Request::uploadAPI(ConversionClient::$baseUrl . '/files', $filename);
37+
$json = json_decode($result, true);
38+
if ($json['error'] !== NULL) {
39+
throw new \Exception('File Upload Error: ' . $json['error']);
40+
}
41+
$file_id = $json['file_id'];
42+
return $file_id;
43+
}
44+
45+
public static function downloadFile($file_id, $filename)
46+
{
47+
Request::downloadAPI(ConversionClient::$baseUrl . "/files/$file_id", $filename);
48+
}
49+
}

src/ConversionClient.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
namespace ConversionTools;
4+
5+
class ConversionClient
6+
{
7+
const VERSION = '1.0.0';
8+
9+
public static $userAgent = 'conversiontools-php';
10+
11+
public static $baseUrl = 'https://api.conversiontools.io/v1';
12+
13+
public static $DEBUG = FALSE;
14+
15+
private static $token;
16+
17+
public function __construct($token)
18+
{
19+
self::$token = $token;
20+
}
21+
22+
public static function getToken()
23+
{
24+
return self::$token;
25+
}
26+
27+
public static function getUserAgent()
28+
{
29+
return self::$userAgent . '/' . self::VERSION;
30+
}
31+
32+
public function convert($type, $fileInput, $fileOutput, $options = NULL)
33+
{
34+
$file_id = API::uploadFile($fileInput);
35+
$task_id = API::createTask($type, $file_id, $options);
36+
while (TRUE) {
37+
list($status, $file_id_result) = API::getTaskStatus($task_id);
38+
switch ($status) {
39+
case 'SUCCESS':
40+
API::downloadFile($file_id_result, $fileOutput);
41+
return;
42+
case 'ERROR':
43+
return;
44+
}
45+
sleep(5);
46+
}
47+
}
48+
}

src/Request.php

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
<?php
2+
3+
namespace ConversionTools;
4+
5+
class Request
6+
{
7+
private function initialize($method, $url, $headers, $data = NULL)
8+
{
9+
$ch = curl_init();
10+
curl_setopt($ch, CURLOPT_URL, $url);
11+
if ($method === 'GET') {
12+
curl_setopt($ch, CURLOPT_HTTPGET, 1);
13+
} else if ($method === 'POST') {
14+
curl_setopt($ch, CURLOPT_POST, 1);
15+
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
16+
}
17+
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
18+
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
19+
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
20+
21+
return $ch;
22+
}
23+
24+
private function handleErrorCode($ch)
25+
{
26+
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
27+
$message = curl_error($ch);
28+
$code = curl_errno($ch);
29+
30+
if ($code !== 0) {
31+
throw new \Exception('Request Error: ' . $message);
32+
}
33+
34+
if ($httpCode !== 200) {
35+
throw new \Exception('HTTP Status Code: ' . $httpCode);
36+
}
37+
38+
if (ConversionClient::$DEBUG === TRUE) {
39+
if ($code != 0) {
40+
print "CURL Code: $code\n";
41+
print "Message: $message\n";
42+
}
43+
print "HTTP Code: $httpCode\n";
44+
print "Response: $response\n";
45+
}
46+
}
47+
48+
private static function makeRequest($method, $url, $headers, $data = NULL)
49+
{
50+
$ch = self::initialize($method, $url, $headers, $data);
51+
$response = curl_exec($ch);
52+
self::handleErrorCode($ch);
53+
curl_close($ch);
54+
return $response;
55+
}
56+
57+
private static function makeFileDownloadRequest($method, $url, $headers, $filename)
58+
{
59+
$fh = fopen($filename, 'wb');
60+
if (!$fh) {
61+
throw new \Exception("Cannot open file $filename");
62+
}
63+
$ch = self::initialize($method, $url, $headers);
64+
curl_setopt($ch, CURLOPT_FILE, $fh);
65+
$response = curl_exec($ch);
66+
fclose($fh);
67+
self::handleErrorCode($ch);
68+
curl_close($ch);
69+
70+
return;
71+
}
72+
73+
private static function prepareHeaders()
74+
{
75+
$headers = [
76+
'Authorization: Bearer ' . ConversionClient::getToken(),
77+
'User-Agent: ' . ConversionClient::getUserAgent(),
78+
];
79+
return $headers;
80+
}
81+
82+
public static function requestAPI($method, $url, $data=NULL)
83+
{
84+
$headers = self::prepareHeaders();
85+
array_push($headers, 'Content-Type: application/json');
86+
$response = self::makeRequest($method, $url, $headers, $data);
87+
return $response;
88+
}
89+
90+
public static function uploadAPI($url, $filename)
91+
{
92+
$headers = self::prepareHeaders();
93+
array_push($headers, 'Content-Type: multipart/form-data');
94+
if (function_exists('curl_file_create')) { // For PHP 5.5+
95+
$file = curl_file_create($filename);
96+
} else {
97+
$file = '@' . realpath($filename);
98+
}
99+
$data = ['file' => $file];
100+
$response = self::makeRequest('POST', $url, $headers, $data);
101+
return $response;
102+
}
103+
104+
public static function downloadAPI($url, $filename)
105+
{
106+
$headers = self::prepareHeaders();
107+
self::makeFileDownloadRequest('GET', $url, $headers, $filename);
108+
}
109+
}

0 commit comments

Comments
 (0)