1 – Before Getting Started

This is article 1 of the YouTube API With PHP series.

PROGRAMMING LEVEL

As a PHP programmer, you are expected to be familiar with the following concepts to use the YouTube API:

  • Using cURL to make HTTP GET and POST requests
  • Handle data in the JSON format (explained in the next section)
  • Familiarity with associative arrays

Actually if you go through the official YouTube API documentation, it looks very complex and intimidating, but it is not really like that. This book is meant to make it simple and logical.

You also need to be conversant with Javascript as some of the API components like the Player API only work with Javascript. Knowledge of JQuery is definitely a plus point but not compulsory in this case.

 

THE JSON DATA FORMAT

All data returned by the YouTube API is in the JSON format.  JSON stands for Javascript Object Notation and is a very popular way of storing and retrieving data across many platforms and languages. The main advantage of JSON is that it is plain text using standard ASCII code, which means that it is usable on any computer or operating system.

PHP provides native support for JSON handling since version 5.2. If you are already familiar on how to work with JSON data in PHP, then you can skip this entire article. If not then you can go through the small tutorial section below:

JSON Functions

 PHP provides 4 built-in functions to work with JSON.

  • json_decode() – Decode a JSON string
  • json_encode() – Encode a string into JSON
  • json_last_error_msg() – the last error message during a json_decode() or json_encode function
  • json_last_error() – the last error code during a json_decode() or json_encode function

Encoding to JSON

Let’s run this code:

echo(json_encode("This is a string"));

 

Output:

“This is a string”

 

Now, as you can see, encoding any primitive data type like a string or integer as JSON will always show it as a string, which is not of any practical use.

JSON encoding is only useful when used with data structures, like a class or an array. What JSON encoding does is that it converts everything into a string based structure.

The code below shows how this works with various data structures:

<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_WARNING);
$s = "This is a string";
echo(json_encode($s) . "<br>");
$arr = array("One", "Two", "Three");
echo(json_encode($arr) . "<br>");

$arr2 = array("one"=>100, "two"=>200, "three"=>300);
echo(json_encode($arr2) . "<br>");


$obj = new MyClass();
$obj->id = 1;
$obj->name = "My Name";
$obj->registration = date("Y-m-d");

echo(json_encode($obj) . "<Br>");

//////////


class MyClass {
public $id = 0;
public $name = "";
public $registration = null;

}


?>

 

The output:

“This is a string”

[“One”,”Two”,”Three”]

{“one”:100,”two”:200,”three”:300}

{“id”:1,”name”:”My Name”,”registration”:”2017-05-15″}

 

Note that all results of json_encode() are strings.

 

Decoding from JSON

To convert JSON data back into its original structural format we use the json_decode() function. The code below runs a json_decode on various data types, after running a json_encode on them.

<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_WARNING);
$s = "This is a string";
$sJSON = json_encode($s);
$arr = array("One", "Two", "Three");
$arrJSON = json_encode($arr);
$arr2 = array("one"=>100, "two"=>200, "three"=>300);
$arr2JSON = json_encode($arr2);


$obj = new MyClass();
$obj->id = 1;
$obj->name = "My Name";
$obj->registration = date("Y-m-d");

$classJSON = json_encode($obj);

echo(json_decode($sJSON) . "<br>");
echo(json_decode($arrJSON). "<br>");
echo(json_decode($arr2JSON).  "<br>");
echo(json_decode($classJSON).  "<br>");

//////////

class MyClass {
public $id = 0;
public $name = "";
public $registration = null;

}


?>

 

The Output:

This is a string

Array

Catchable fatal error: Object of class stdClass could not be converted to string in /var/websites/test/YouTubeapi/json/test-json2.php on line 24

 The string converted back into a string. The array shows as Array because we are trying to use echo() to display an array.

However the second array failed to be decoded. $arr2 is an associative array. By default json_decode() tries to decode structures into stdClass instead of an array. Since the original structure was an array, it fails when json_decode tries to convert it into stdClass. To force json_decode to generate an associative array, we pass a second parameter as true. The second parameter is $assoc=false by default. So by passing it as true, we get our associative array back.

 

So if we change

echo(json_decode($arr2JSON).  "<br>");

to

echo(json_decode($arr2JSON, true).  "<br>");

then the output becomes:

This is a string

Array

Array

Catchable fatal error: Object of class stdClass could not be converted to string in /var/websites/test/YouTubeapi/json/test-json2.php on line 25

 

Now we have to see why the class did not get decoded. stdClass is the generic default empty class in PHP, but unlike in Java where the default Object is the parent  of every user-defined class , stdClass is not the universal parent of a user-defined class. So the class MyClass cannot be cast into stdClass and an exception is thrown. To get back the original $obj from $classJSON , we have to do two things:

  1. Get an associative array back from json_decode
  2. Convert that associate array into an object of MyClass

We need two lines of code for the above:

$classAsArray = json_decode($classJSON, true);
$obj = new MyClass();
foreach ($classAsArray as $key => $value)
 $obj->{$key} = $value;



Let us replace all the echo statements with var_dump and then see the output:

 

<?php

error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_WARNING);


$s = "This is a string";

$sJSON = json_encode($s);


$arr = array("One", "Two", "Three");

$arrJSON = json_encode($arr);


$arr2 = array("one"=>100, "two"=>200, "three"=>300);

$arr2JSON = json_encode($arr2);



$obj = new MyClass();

$obj->id = 1;

$obj->name = "My Name";

$obj->registration = date("Y-m-d");


$classJSON = json_encode($obj);



var_dump(json_decode($sJSON));

echo("<br>");

var_dump(json_decode($arrJSON));

echo("<br>");


var_dump(json_decode($arr2JSON, true));

echo("<br>");


$classAsArray = json_decode($classJSON, true);

$obj = new MyClass();

foreach ($classAsArray as $key => $value)

$obj->{$key} = $value;


var_dump($obj);

echo("<br>");


//////////


class MyClass {

public $id = 0;

public $name = "";

public $registration = null;

}


?>

 

The output:

string(16) “This is a string”

array(3) { [0]=> string(3) “One” [1]=> string(3) “Two” [2]=> string(5) “Three” }

array(3) { [“one”]=> int(100) [“two”]=> int(200) [“three”]=> int(300) }

object(MyClass)#2 (3) { [“id”]=> int(1) [“name”]=> string(7) “My Name” [“registration”]=> string(10) “2017-05-15” }

 

Error Handling

Normally we can check if a json_encode() or json_decode worked by checking the result. If it is null then it means there was an error. If you need to know the reason for the failure, you can use the json_last_error() and json_last_error_msg() functions.

 

The first gives you an error code . You can find a list of the error codes on http://php.net/manual/en/function.json-last-error.php

 

The second function gives you a string description of the error message.
 

 
<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_WARNING);
$arr2 = "{asdasd:asdasdas+10101";
$jsonToArr = json_decode($arr2);

echo("result=" . $jsonToArr . "<br>");
echo("Error=" . json_last_error() . "<br>");
echo("Error Message =" . json_last_error_msg() . "<br>");

?>

The Output:

result=

Error=4

Error Message =Syntax error

 

This concludes our small tutorial on how to handle JSON data in PHP.

Be the first to comment

Leave a Reply

Your email address will not be published.


*