The oembed system is trending in the field of Open API technology and will be trending along with Web and App Development. This is a very powerful concept with minimal coding effort on the development side. Often referred to as oEmbed system this method provides useful information to the developer with just a simple request. The response given is usually in the form of raw Array, JSON or XML.
oEmbed with PHP?
Its simple. We will be using PHP to get information by streaming to the API server to make the application more realistic!
There are many ways in which you can achieve the target which is to fetch required data from the response. In this tutorial we will be looking into Youtube, Soundcloud and Flickr to show an example of a video, audio and a photo. Check out oEmbed to grab a brief idea about the Request URL for each provider. Let us now see the Request URL Parameters for each mentioned. Every request will contain three parts in the URL,
URL : The provider of the API (Ex: http://www.youtube.com/oembed)
- url: Link of the video
- format: Denotes the format in which you want the response. Here you can use either json or xml
First you need to send a request to the youtube’s oembed URL. We will be using the following URL
$video_url = 'https://www.youtube.com/watch?v=BKDAm3AC97s';
$url = 'http://www.youtube.com/oembed?url='.rawurlencode($video_url).'&format=json';
$opts = array('https' =>
'method' => 'GET',
'max_redirects' => '0',
'ignore_errors' => '1',
$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);
$data = json_decode(stream_get_contents($stream));
We first set the request URL in the $url variable. You can notice that I have encoded the video link using rawurlencode so as to escape errors. Try removing it to see what error occurs. Next form an array of options to be sent while streaming for the API response, for detailed information see HTTP Stream.
Having set up the stream let us now try to open the video with fopen(). If fopen() fails to read the URL given it will throw an error. r denotes that we only need to read the URL. Now apply stream_get_contents() on fopen() and pull all data coming from the stream as a response. At this point you have all data received and ready to access the video. There is one last step! Just convert the response JSON into PHP array to access the objects. json_decode the received data and store it in a variable.
<div style="width:640px;height:auto;margin:0 auto">
<?php echo $data->html; ?>
Be sure to use $data->html which will get only the html object from the response which contains the required iframe element.
For flickr and soundcloud follow the same method. You can check all three example in the preview page. I hope this tutorial would be helpful for beginners out there 🙂