Skip to content

Commit 0d389ce

Browse files
committed
Ready to use
1 parent 78a44e0 commit 0d389ce

File tree

3 files changed

+362
-2
lines changed

3 files changed

+362
-2
lines changed

README.md

Lines changed: 97 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,97 @@
1-
# json2video-php-sdk
2-
PHP SDK for JSON2Video API
1+
# Create videos programmatically in PHP
2+
Create and edit videos: add watermarks, resize videos, create slideshows, add soundtrack, automate the creation of videos in multiple languages, add voice-over, add text animations.
3+
4+
JSON2Video API is the easiest way to create, edit and customise videos programmatically. Its dead simple approach, close to the web development mindset, makes it the ultimate solution for developers that want to create or customise videos in an automated way.
5+
6+
Additionally, the simple integration of real HTML5+CSS elements, the already built-in text animations and voice generation (TTS) converts JSON2Video in the best solution in its category.
7+
8+
Use cases
9+
* Automate the production of promotional videos for your e-commerce products
10+
* Automate publication of social media videos created directly from your news feed
11+
* Customize your advertising campaigns with different images, videos, texts and create tens or hundreds of different options
12+
* From weather forecasts to traffic bulletins or financial reports, if you have a data source you can create an audiovisual experience
13+
* Convert your text, pictures and information into engaging videos of your real estate properties
14+
* Add watermarks, bumpers, titles; Concatenate different videos into one; Add voice-over or music; Create photo slideshows; …
15+
16+
17+
## Get your FREE API Key
18+
JSON2Video is free to use. Get your API Key at [JSON2Video.com](https://json2video.com)
19+
20+
## Documentation
21+
The [API Specification](https://json2video.com/docs/api/) will provide you with all the details of the JSON payload and the endpoints.
22+
23+
For a step by step guide, read the [Tutorial](https://json2video.com/docs/tutorial/) that will introduce you through all features with code examples.
24+
25+
## PHP SDK installation
26+
You can use JSON2Video PHP SDK as a Composer package or with a simple require_once.
27+
28+
### Using require_once
29+
The simplest way :-)
30+
31+
1) Download all.php from the /bundled folder into your project directory
32+
2) Import the library:
33+
34+
```php
35+
<?php
36+
require_once 'path/to/the/sdk/all.php';
37+
38+
```
39+
40+
### Using Composer
41+
The SDK has no external dependencies on other packages.
42+
43+
1) Open the terminal and cd to your project directory
44+
2) Use composer:
45+
46+
```
47+
$ composer require json2video/json2video-php-sdk
48+
```
49+
50+
## Hello world
51+
JSON2Video makes video creation easy as a piece of cake:
52+
53+
```php
54+
<?php
55+
// Create a new movie
56+
$movie = new Movie;
57+
58+
// Set your API key
59+
// Get your free API key at https://json2video.com
60+
$movie->setAPIKey(YOUR_API_KEY);
61+
62+
// Set a project ID
63+
$movie->project = 'myproj';
64+
65+
// Set movie quality: low, medium, high
66+
$movie->quality = 'high';
67+
68+
// Create a new scene
69+
$scene = new Scene;
70+
71+
// Set the scene background color
72+
$scene->background_color = '#4392F1';
73+
74+
// Add a text element printing "Hello world" in a fancy way (basic/006)
75+
// The element is 10 seconds long and starts 2 seconds from the scene start
76+
// Element's vertical position is 50 pixels from the top
77+
$scene->addElement([
78+
'type' => 'text',
79+
'template' => 'basic/006',
80+
'items' => [
81+
[ 'text' => 'Hello world' ]
82+
],
83+
'y' => 50,
84+
'duration' => 10,
85+
'start' => 2
86+
]);
87+
88+
// Add the scene to the movie
89+
$movie->addScene($scene);
90+
91+
// Call the API and render the movie
92+
$movie->render();
93+
```
94+
95+
This is the resulting video:
96+
97+
https://assets.json2video.com/mkt/github/hello-world.mp4

bundled/all.php

Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
<?php
2+
3+
/*
4+
5+
JSON2Video PHP SDK
6+
7+
This simple SDK is a wrapper for calling JSON2Video API
8+
JSON2Video API allows you to create and edit videos programmatically
9+
10+
Documentation: https://json2video.com/docs/sdk
11+
12+
*/
13+
14+
namespace JSON2Video;
15+
16+
class Base {
17+
18+
protected $object, $properties;
19+
20+
public function __get($property) {
21+
$property = strtolower($property);
22+
if (in_array($property, $this->properties) && isset($this->object[$property])) {
23+
return $this->object[$property];
24+
}
25+
26+
return null;
27+
}
28+
29+
public function __set($property, $value) {
30+
$property = strtolower($property);
31+
if (in_array($property, $this->properties)) {
32+
$property = strtolower(str_replace('_', '-', $property));
33+
$this->object[$property] = $value;
34+
return $value;
35+
}
36+
37+
return null;
38+
}
39+
40+
public function addElement($element=null) {
41+
if ($element && is_array($element)) {
42+
if (!isset($this->object['elements'])) $this->object['elements'] = [];
43+
$this->object['elements'][] = $element;
44+
return true;
45+
}
46+
return false;
47+
}
48+
49+
public function getJSON() {
50+
return json_encode($this->object, JSON_PRETTY_PRINT);
51+
}
52+
53+
public function getObject() {
54+
return $this->object;
55+
}
56+
}
57+
58+
59+
class Scene extends Base {
60+
protected $properties = ['comment', 'background_color', 'duration', 'cache'];
61+
62+
protected $object = [];
63+
64+
public function setTransition($style=null, $duration=null, $type=null) {
65+
if ($style || $duration || $type) {
66+
if (!isset($this->object['transition'])) $this->object['transition'] = [];
67+
if (!is_null($style)) $this->object['transition']['style'] = $style;
68+
if (!is_null($duration)) $this->object['transition']['duration'] = $duration;
69+
if (!is_null($type)) $this->object['transition']['type'] = $type;
70+
}
71+
}
72+
73+
}
74+
75+
class Movie extends Base {
76+
private $api_url = 'https://api.json2video.com/v1/movies';
77+
protected $properties = ['comment', 'project', 'width', 'height', 'resolution', 'quality', 'fps', 'cache'];
78+
79+
private $apikey = null;
80+
81+
protected $object = [];
82+
83+
public function setAPIKey($apikey) {
84+
$this->apikey = $apikey;
85+
}
86+
87+
public function addScene($scene=null) {
88+
if ($scene && is_a($scene, 'JSON2Video\Scene')) {
89+
if (!isset($this->object['scenes'])) $this->object['scenes'] = [];
90+
$this->object['scenes'][] = $scene->getObject();
91+
return true;
92+
}
93+
else throw new \Exception('Invalid scene');
94+
return false;
95+
}
96+
97+
private function fetch(string $method, string $url, string $body, array $headers = []) {
98+
$context = stream_context_create([
99+
"http" => [
100+
"method" => $method,
101+
"header" => implode("\r\n", $headers),
102+
"content" => $body,
103+
"ignore_errors" => true,
104+
],
105+
]);
106+
107+
$response = file_get_contents($url, false, $context);
108+
109+
$status_line = $http_response_header[0];
110+
111+
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
112+
113+
$status = $match[1];
114+
115+
return [
116+
'status' => $status,
117+
'message' => $status_line,
118+
'response' => $response
119+
];
120+
}
121+
122+
public function render() {
123+
124+
if (empty($this->apikey)) throw new \Exception('Invalid API Key');
125+
126+
$postdata = json_encode($this->object);
127+
if (is_null($postdata)) {
128+
throw new \Exception('Invalid movie settings');
129+
}
130+
131+
$response = $this->fetch('POST', $this->api_url, $postdata, [
132+
"Content-Type: application/json",
133+
"x-api-key: {$this->apikey}"
134+
]);
135+
136+
if ($response) {
137+
if ($response['status']=='200') return json_decode($response['response'], true);
138+
elseif ($response['status']=='400') {
139+
$api_response = json_decode($response['response'], true);
140+
throw new \Exception('JSON Syntax error: ' . ($api_response['message'] ?? 'Unknown error'));
141+
}
142+
else {
143+
144+
throw new \Exception('API error: ' . ($response['message'] ?? 'Unknown error'));
145+
}
146+
}
147+
else throw new \Error('SDK error');
148+
149+
return false;
150+
}
151+
152+
public function getStatus() {
153+
154+
if (empty($this->apikey)) throw new \Exception('Invalid API Key');
155+
if (empty($this->object['project'])) throw new \Exception('Project ID not set');
156+
157+
$url = $this->api_url . '?project=' . $this->object['project'];
158+
159+
$status = $this->fetch('GET', $url, '', [
160+
"x-api-key: {$this->apikey}"
161+
]);
162+
163+
if ($status) {
164+
if ($status['status']=='200') return json_decode($status['response'], true);
165+
else {
166+
throw new \Exception('API error: ' . ($status['message'] ?? 'Unknown error'));
167+
}
168+
}
169+
else throw new \Error('SDK error');
170+
171+
return false;
172+
}
173+
}

examples/hello-world.php

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
<?php
2+
3+
/*
4+
5+
Simple "Hello world" example demonstrating the usage of the JSON2Video PHP SDK
6+
7+
Documentation: https://json2video.com/docs/sdk
8+
9+
*/
10+
11+
// Import the Movie and Scene classes
12+
use JSON2Video\Movie;
13+
use JSON2Video\Scene;
14+
15+
// Import the SDK
16+
include "../src/json2video-php-sdk.php";
17+
18+
// Get your free API key at https://json2video.com
19+
define ('YOUR_API_KEY', '');
20+
21+
// Create a new movie
22+
$movie = new Movie;
23+
24+
// Set your API key
25+
$movie->setAPIKey(YOUR_API_KEY);
26+
27+
// Set a project ID
28+
$movie->project = "myproj";
29+
30+
// Set movie quality
31+
$movie->quality = "high";
32+
33+
// Create a new scene
34+
$scene = new Scene;
35+
36+
// Set the scene background color
37+
$scene->background_color = "#4392F1";
38+
39+
// Add a text element printing "Hello world" in a fancy way (basic/006)
40+
// The element is 10 seconds long and starts 2 seconds from the scene start
41+
// Element's vertical position is 50 pixels from the top
42+
$scene->addElement([
43+
'type' => 'text',
44+
'template' => 'basic/006',
45+
'items' => [
46+
[ 'text' => 'Hello world' ]
47+
],
48+
'y' => 50,
49+
'duration' => 10,
50+
'start' => 2
51+
]);
52+
53+
54+
try {
55+
// Add the scene to the movie
56+
$movie->addScene($scene);
57+
58+
// Call the API and render the movie
59+
$movie->render();
60+
61+
// Check every 2 seconds for the render status
62+
for ($i=0; $i<60; $i++) {
63+
64+
// Get the movie status
65+
$response = $movie->getStatus();
66+
67+
if ($response['success'] && $response['movies'][0]) {
68+
// Print the status and the last task
69+
echo '>>> Status: ', $response['movies'][0]['status'], ' --> ', $response['movies'][0]['task'], PHP_EOL;
70+
71+
// If the render is done, print the video URL and break the loop
72+
if ($response['movies'][0]['status']=='done') {
73+
echo PHP_EOL, '>>> The movie is ready at: ', $response['movies'][0]['url'], PHP_EOL, PHP_EOL;
74+
break;
75+
}
76+
}
77+
else {
78+
// If there was an invalid API response
79+
echo '--- ERROR ---', PHP_EOL, $response['message'] ?? 'Unknown error', PHP_EOL, PHP_EOL;
80+
}
81+
82+
// Sleep for 2 seconds in every loop
83+
sleep(2);
84+
}
85+
}
86+
catch(Exception $error) {
87+
// Print the error message
88+
echo $error->getMessage(), PHP_EOL;
89+
}
90+
91+
92+

0 commit comments

Comments
 (0)