Showing posts with label JSON. PHP. Show all posts
Showing posts with label JSON. PHP. Show all posts

Monday 6 October 2014

Using PHP to get YouTube Channel feed into Twitter Bootstrap thumbnails

I've been working on a Twitter Bootstrap site. The client created a YouTube channel and wanted the feed coming into the site. Some of the videos added are uploaded by the users, some come from subscriptions. There is a nice class called thumbnail in Twitter Bootstrap for such things, so I thought I'd use that. I'm happiest getting external data using PHP. Here's how it's done.
Replace the word 'Google' with the name of your channel.
<?php
$url = 'https://gdata.youtube.com/feeds/api/videos?q=Google&max-re%20sults=5&v=2&alt=jsonc&orderby=published';
$json = file_get_contents($url);
$data = json_decode($json);
$items = $data->data->items;
foreach($items as $child)
{
echo '<a href="'.$child->player->default.'" class="thumbnail">';
echo '<h4>'.$child->title.'</h4>';
echo '<img src="'.$child->thumbnail->sqDefault.'" alt="'.$child->title.'" />';
echo '<footer>'.date("jS F Y",strtotime($child->updated)).'</footer>';
echo '</a>';
}
?>

Tuesday 2 October 2012

Presenting MySQL table data through PHP, JSON and jQuery

This may seem like a long way round to do something, but believe me, it has its benefits if you are trying to deliver an open systems approach to your development framework.

Let's say I have a MySQL database with table called chat. The chat table has 3 fields; userid, entry and datesaved.

I create a PHP script called jsonout.php which returns all rows of the chat table, thus:

<?php
$con = mysql_connect('localhost','root','');
mysql_select_db('test', $con);
$result = mysql_query('SELECT * FROM `chat`');
while($rows[] = mysql_fetch_assoc($result));
array_pop($rows);
mysql_close($con);
echo json_encode($rows);
?>

Notice the final line (in red) where I return a JSON encoded version of the resulting array.

Now my HTML page (below) can collect the JSON through jQuery and present the results on the page.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple JSON retrieval through jQuery</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
 font:10px/15px Sans-serif;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
 google.load("jquery", "1");
</script>
</head>
<body>
<script>
(function()
{
 $.getJSON('jsonout.php', function(data)
 {
    $.each(data, function(i, items)
    {
      $('body').append('<p>'+items.userid+'</p>'+items.entry+'<p>'+items.datesaved+'</p>');
    });
 });
})();
</script>
</body>
</html>

Monday 7 November 2011

Getting single row results MySQL using PHP

I'm always using this code. Sometimes I know there should be/is only one record returned from my MySQL query. Especially if I have specified 1 result as in the query below. As long as I know the resulting column names, this is a very useful technique.

<?php

$query = mysql_query("SELECT * FROM `users` WHERE `username` = '{$username}' LIMIT 1;");
$row = mysql_fetch_assoc($query);
echo 'Hello '.$row['firstname'];
?>

Friday 22 July 2011

Use PHP to get the current web address without the filename

Sometimes I need to grab the current web path without the current file name in order to pass a string in an email. As an example the current default location is http://www.effectivewebdesigns.co.uk/index.php, but in the future it may be http://www.effectivewebdesigns.co.uk/index.html or http://www.effectivewebdesigns.co.uk/default.html so sometimes I need to future proof.

<?php
$webAddress = 'http://'.$_SERVER['SERVER_NAME'];
$webAddress .= $_SERVER['REQUEST_URI'];
$webAddress = substr($webAddress, 0, 0-(strlen(basename($_SERVER['REQUEST_URI']))));
echo $webAddress;
?>

Lorem and Gibberish through PHP using the randomtext.me JSON API

Crikey! Is it so long since I did a post. OK. Here is yet another way of getting Lorem Ipsum or Gibberish to your page, while you test it out. There is a great generator at http://www.randomtext.me/ and they have helpfully supplied us with a JSON based API.

Below is an example ho grabbing 7 paragraphs of gibberish between 30 and 50 characters long. I then echo them to the page.


<?php
$data = json_decode(file_get_contents("http://www.randomtext.me/api/gibberish/p-7/30-50"));
echo $data->text_out;
?>

Monday 27 June 2011

PHP Form, jQuery, working in IE

Some days, you start by saying, "'I'll just get this out of the way, then I can concentrate on something heavier". You then write code without testing because you know how it works, and apart from a little syntax change, you get it working fine. About 15 minutes. This was my experience with writing a page with a form. It stored the data in a text file, then updated the page tag with the new contents. It worked fine in Chrome and Firefox. Then the dreaded IE pulled me back. 3 hours later, I find the solution. Below are code examples to a common problem.
Create a html form.
On submission, write the contents of the form to a file.
Once the file has been updated, refresh a section showing the new content.

Here is the code for readdata.php. Notice the @ before file_get_contents. This suppresses a warning if the file does not already exist.

<?php
foreach (explode("\n", @file_get_contents('data.data')) as $value)
{
echo $value."<br />";
}
?>
Here is the code for writedata.php. Nothing particularly clever here.

<?php
file_put_contents('data.data', $_POST['stuff']."\n", FILE_APPEND);
?>
Now to the main page. A few of important items here:
  1. Only $.get works in IE .load doesn't.
  2. $.ajaxSetup({cache: false}) is also required for IE otherwise you get all sorts of content varients coming through.
  3. I used the jQuery Form Plugin from http://jquery.malsup.com/form/ It saves a lot of problems.


Have fun.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Read and write using jquery</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script type="text/javascript" src="jquery.form.js"></script>
<script>
$.fn.readStuff = function()
{
$.get('readdata.php', null, function(data)
{
    $('section').html(data);
});
$('#stuff').val('');
}
$(document).ready(function()
{
$.ajaxSetup({cache: false});
$('form').ajaxForm(function()
{
$(this).readStuff();
});
});
</script>
</head>
<body>
<h1>PHP and jQuery read/write test</h1>
<h2>Write data</h2>
<form action="writedata.php" method="POST">
<input type="text" name="stuff" id="stuff" />
<input type="submit" />
</form>
<h2>Read data</h2>
<section>
<?php
include 'readdata.php';
?>
</section>
</body>
</html>

Friday 17 June 2011

Using PHP to create a dynamic page navigation based on filenames

Here is the problem. You create a bunch of pages. You want to highlight the current page within the navigation. You don't want to manually change the navigation elements to each page.

See demo.

In the example below I create an associative array which contains two elements:

  1. The name of the page which the navigation points to.
  2. The name which should appear in the navigation.

I then grab the filename of the of the current page in the browser.
I then traverse the associative array, each time comparing the filename against the current file shown in the browser, each time creating an anchor using the values.

If array filename and current page filename are the same, then I add a CSS ID to the anchor tag.

You will need to write a little CSS to highlight the current page anchor such as:

nav a#activeMenuItem
{
background:#EEEEEE;
}


But other than that, it works like a charm. Have fun!


<nav>
<?php
$navArray = array('index.php'=>'home', 'services.php'=>'services','portfolio.php'=>'portfolio','contact.php'=>'contact');
$fileName = substr(strrchr($_SERVER['SCRIPT_NAME'],47),1);
foreach($navArray as $fname => $linktitle)
{
echo '<a href="'.$fname.'"';
if($fname==$fileName)
{
echo ' id="activeMenuItem"';
}
echo '>'.$linktitle.'</a>';
}
?>
</nav>

Wednesday 6 April 2011

Using YQL with PHP

I've just started to look into YQL. It looks very powerful but some of the videos an tutorials are a bit dry. There are some missing links which I'm hoping to expose in how to implement with PHP. It should be possible to use YQL for your applications very easily, but at the moment I'm finding my way around it. Part of the problem seems to be around not knowing the structure of the returned JSON before you have to present it. We'll see. Below is an example of calling some YQL on a single web page and displaying the paragraphs within it. I call a very simple PHP GET using CURL. Then I loop through the resulting JSON object until I reach the paragraphs.
Good luck!


<?php
$api = 'http://query.yahooapis.com/v1/public/yql?q=';
$query = 'select * from html where url="http://www.stream-idc.net/"';
$params = '&format=json';

$session = curl_init($api.urlencode($query).$params);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);  
$json = curl_exec($session);
curl_close($session);
$yqlObj =  json_decode($json);

if(!is_null($yqlObj->query->results))
{
foreach($yqlObj->query->results->body->p as $bodyContent)
{
echo $bodyContent->{'content'};
}
}
?>

Monday 28 March 2011

Google TTS API for my paragraphs using HTML5, jQuery and PHP

Most of the credit for this post goes to Abu Ashraf Masnun for this post http://www.masnun.me/2009/12/14/googles-text-to-speech-api-a-php-wrapper-class.html
You'll need to take a copy of his code for this to work. Then you need to append the following lines to the end of the PHP (after his object declaration).
$tts = new TextToSpeech();
$tts->setText($_POST['text']);
$tts->saveToFile("masnun.mp3");

Once you've done this, you can create a HTML file like mine below. To use the page, click on the speaker icons.

Note:This will not work in rubbish browsers. For this you will need to change my HTML5 <audio> tag for something awful like the <object> tag.

Another note:The Google TTS has a 100 character limit.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text to speech</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style>
body
{
font-family:Sans-serif;
line-height:1.5em;
}
</style>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
</script>
<script>
var audioText = '<audio controls="controls" autoplay="autoplay">';
audioText += '<source src="masnun.mp3" type="audio/mpeg" />';
audioText += 'Your browser does not support the audio element.';
audioText += '</audio>';
$(document).ready(function()
{
$('.tts').each(function()
{
$(this).after('<a href="#" class="speaker"><img src="http://farm6.static.flickr.com/5091/5568186294_a396c02f4f_t.jpg" /></a>');
});
$('.speaker').click(function()
{
$.post('tts.php',
{
text:$(this).prev('p').text()
}, function(data)
{
$(this).after(audioText);
});
return false;
});
});
</script>
</head>
<body>
<section id="mainContent">
<p class="tts">Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.</p>
<p class="tts">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
<p class="tts">Johnny Diamond. Peter Sam</p>
</section>
</body>
</html>

Wednesday 2 February 2011

Sharing data from the Facebook API

In the simple example below I am sending a request to Facebook through the Graph API. I supply my App ID. In return, Facebook provides me with a JSON object. I then process the JSON, using PHP to create a link to my Facebook application. Simple I know, and but that's the point.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="UTF-8">
<title>Sharing data from the Facebook API</title>
<!--[if IE]>
 <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="http://meyerweb.com/eric/tools/css/reset/reset.css" />
<style type="text/css">
</style>
</head>
<body>
<?php
$url = 'https://graph.facebook.com/yourAppID';
$JSONobj = json_decode(file_get_contents($url));
echo '<hr />';
echo '<a href="';
echo $JSONobj->{'link'};
echo '">';
echo $JSONobj->{'name'};
echo ' Facebook page</a>';
?>
</body>
</html>

A beginners guide to get your website working with Facebook

Below are 3 steps to :

  1. Get Facebook functionality into your website.
  2. Have a Facebook application presence for your website.

Step 1 :
Register your website to get an AppID here http://developers.facebook.com/setup/
Receieve your AppID and App secret.
You also get an example page with a login and like plugin, which you can extract and embed into your site.

Step 2 :
Seeing this in action gives you the confidence to move to the next stage. You can go to http://developers.facebook.com/docs/plugins. Here you will see other plugins which can be easily embeded into your site. Some of these plugins are designed to work in co-ordination with the Facebook Page you get with your application ID. This is available through http://www.facebook.com/apps/application.php?id=yourAppID

Step 3 :
You may also access the Social Graph API. Documentation of which resides here http://developers.facebook.com/docs/api. An example being that using https://graph.facebook.com/yourAppID will return JSON data about your application.
If for example, your website uses PHP, you may process this JSON data and represent it on your website.

Friday 19 November 2010

PHP API call to Summarity

Summarity at http://www.summarity.com/ is software which summarises items of text. They helpfully provide an API for developers to use. There is an example of how to call the API using python on the website. I don't use python. I use PHP. So I went about writing the API call in PHP. So below is an example of how it's done. You will need to get your own API key. I hope it's obvious where to add your text string.

<?php

 $url = 'http://summarity.com/apiV1';
 $data = 'summarity_api_key=yourAPIkey';
 $data .= '&text='.urlencode('Just some text for testing');
                 
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                
 $response = curl_exec($ch);                
 curl_close($ch);
 echo(json_decode($response));
?>