PHP, MySQL, Drupal, .htaccess, Robots.txt, Phponwebsites: JSON
JSON - phponwebsites.com
Showing posts with label JSON. Show all posts

18 Apr 2015

Create Search API like itunes Search API using PHP and MySQL

                      The Apple itunes provided a search API for retrieve app information from it. The Apple search API display result as JSON format. Do you want to know more information about Apple itunes search API, then visit iTunes Search API.

                      You can also create search API like Apple itunes search API if you know how to create JSON file using PHP. Due to this, you can provide search API for your websites. If you didn't know create JSON file using PHP and MySQL, then visit How to get output as JSON format using PHP and Mysql.

Generate Search API using PHP and MySQL


                       Lets see how to create search API using PHP.  Follow below steps to generate search API for your websites using PHP.

Step1: Connect MySQL database using PHP


                     Connect your MySQL database to get stored values from it using PHP. The PHP code for connect MySQL database is below:

 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('fitness') or die(mysql_error());


Step2: Get value from url using PHP


                     While user search something on your search API, you need to get those values for search from url. So only you can provide particular results from your MySQL database. This is done by below PHP code.

 $field=$_REQUEST['field'];
 $limit=$_REQUEST['limit'];

Step3: Make MySQL select query


                     After got values from url, you've to make MySQL query to select corresponding results from database. You can get zero or more than one values from urls for search. You should make MySQL query like below using PHP.

 if($field!='' && $limit!='')
 {
   $cond="where name='".$field."' order by id desc limit 0, $limit";
 }
 if($field=='' && $limit!='')
 {
   $cond="order by id desc limit 0, $limit";
 }
 if($field!='' && $limit=='')
 {
   $cond="where name='".$field."' order by id desc limit 0, 50";
 }
 if($field=='' && $limit=='')
 {
   $cond="order by id desc limit 0, 50";
 }
 $q=mysql_query("select * from f_img $cond") or die(mysql_error());

Step4: Add header for get output as JSON format


              You must add header type ato your PHP script for get output as JSON format. This is like below

 header('Content-Type: Application/json');

Step5: Add content to JSON file using PHP


               You need to create 2 array for create output as multidimensional array. Retrieve values from query result using mysql_fetch_arrayThen you push values to array using array_push() in PHP. Finally encode the results to display output as JSON format using json_encode().

               The full PHP code for create search API is represented below,


<?php
 error_reporting('E_ALL ^ E_NOTICE');
 mysql_connect('localhost','root','') or die(mysql_error());
 mysql_select_db('fitness') or die(mysql_error());
 $field=$_REQUEST['field'];
 $limit=$_REQUEST['limit'];
 if($field!='' && $limit!='')
 {
   $cond="where name='".$field."' order by id desc limit 0, $limit";
 }
 if($field=='' && $limit!='')
 {
   $cond="order by id desc limit 0, $limit";
 }
 if($field!='' && $limit=='')
 {
   $cond="where name='".$field."' order by id desc limit 0, 50";
 }
 if($field=='' && $limit=='')
 {
   $cond="order by id desc limit 0, 50";
 }
 $q=mysql_query("select * from user $cond") or die(mysql_error());
 header('Content-Type: Application/json');
 $details=array();
 $user=array();
 while($res=mysql_fetch_array($q))
 {
  $user['name']=$res['name'];
  $user['state']=$res['state'];
  $user['country']=$res['country'];
  array_push($details,$user);
 }
 //print_R($details);
 echo json_encode($details);

?>


           Your JSON output should be like below,


[
 {"name":"Clark","state":"California","country":"USA"},
 {"name":"Anderson","state":"Los Angeles","country":"USA"},
 {"name":"Smith","state":"London","country":"United Kingdom"},
 {"name":"Jones","state":"Cambridge","country":"United Kingdom"},
 {"name":"Nathan","state":"Franche Comte","country":"France"},
 {"name":"Marie","state":"Paris","country":"France"},
 {"name":"Nastya","state":"St Petersburg ","country":"Russia"},
 {"name":"Dima","state":"Moscow","country":"Russia"},
 {"name":"Linh","state":"Hanoi","country":"vietnam"},
 {"name":"Hoang","state":"Hai Phong","country":"vietnam"},
]

Step6 : .htaccess


                   Add following lines to your .htaccess file


RewriteRule ^search search.php [L]

                  Now you entered search on address bar, the .htaccess redirects you to search.php file. You can get search API using below url types.

                http://www.phponwebsites.com/search?field=nathan&limit=10
                http://www.phponwebsites.com/search?field=nathan
                http://www.phponwebsites.com/search?limit=10
                http://www.phponwebsites.com/search

21 Mar 2015

Get app details from Apple itunes using php

                       You can store games, music album in Apple itunes. If you want to display information of some games or music album, then you can retrieve information about apps from itunes. For retrieve app information from itunes, Apple itunes provided a search API. Do you want to know more information about Apple itunes search API, then visit iTunes Search API.
     
                       On Apple itunes search API, they show some examples for search link like https://itunes.apple.com/search?term=jack+johnson. You can see the result of search API while visiting that page.

                       The Apple Search API return results as JSON format. You need to get app data from JSON file. It is like how you retrieve data from JSON files. You can retrieve required app information from JSON file using PHP.


Retrieve app information from Apple itunes search API using PHP


                       Suppose you have games on Apple itunes storage. Then you can get app details from itunes using PHP. Due to search API, you can Game name, Game description, seller of game, game image, screenshots, game category, released date, price, version, compatibility, rating for game, game category, game url , currency and also language.

Search url in search API


                       You can't get values from search API using only "term" field in your search url.
ie,
        https://itunes.apple.com/search?term=fabsys

      where, you used only term filed to retrieve data from search API. But it didn't give any results. Just view that page on browser.

                      Instead, you have to use add field "country and entity"  . Now your search url look like this
https://itunes.apple.com/search?term=fabsys&country=us&entity=software .

                     Now view this page on your browser. You can get 50 results. This is the default limit. This is the maximum value that you can retrieved. You can also limit the values using "limit" field.

<?php
       $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2");
      $json = json_decode($content, true);
      print_R($json);
?>


Now you will get output on screen like this,


Array ( [resultCount] => 2
           [results] => Array (
   [0] => Array (
    [kind] => software
             [features] => Array ( [0] => iosUniversal )
 [supportedDevices] => Array (
                 [0] => iPhone5s
[1] => iPhone5c
[2] => iPadThirdGen4G
[3] => iPadFourthGen4G
[4] => iPhone-3GS
[5] => iPhone4
[6] => iPadMini4G
[7] => iPadWifi
[8] => iPadThirdGen
[9] => iPhone5
[10] => iPodTouchThirdGen
[11] => iPhone4S
[12] => iPadFourthGen
[13] => iPad23G
[14] => iPad3G
[15] => iPad2Wifi
[16] => iPodTouchFifthGen
[17] => iPodTouchourthGen
[18] => iPadMini
  )
[isGameCenterEnabled] => [artistViewUrl] => https://itunes.apple.com/us/artist/fabsys-technologies-private/id734671920?uo=4
[artworkUrl60] => http://a74.phobos.apple.com/us/r30/Purple4/v4/95/3b/c9/953bc9ac-a10c-1e9e-843d-87dcceb0d07a/Icon.png
[screenshotUrls] => Array (
                  [0] => http://a2.mzstatic.com/us/r30/Purple2/v4/8e/94/e2/8e94e26a-6ac1-3fb1-a4f5-0445e18d3b50/screen1136x1136.jpeg
  [1] => http://a3.mzstatic.com/us/r30/Purple/v4/c4/82/c1/c482c10f-2afd-eb68-c87f-ad2452fc1723/screen1136x1136.jpeg
  )
                 [ipadScreenshotUrls] => Array (
                  [0] => http://a1.mzstatic.com/us/r30/Purple4/v4/46/4d/eb/464deb4e-a26c-2ee8-2484-ad9743d27531/screen480x480.jpeg
  [1] => http://a3.mzstatic.com/us/r30/Purple4/v4/72/01/dd/7201dd31-ee4e-c1f0-8061-4d033d9b427b/screen480x480.jpeg
  )
[artworkUrl512] => http://a1367.phobos.apple.com/us/r30/Purple2/v4/05/73/db/0573db7e-967a-08af-5804-0ecbb38bac77/mzl.tbuwotsy.png
[artistId] => 734671920
[artistName] => Fabsys Technologies Private Limited
[price] => 0
[version] => 42.0
[description] => The worst case scenario is that you are trapped in the room full of disgusting and smelly clothes that is giving you nausea. Find a way to escape from this room before you kill yourself
[currency] => USD
[genres] => Array ( [0] => Games [1] => Puzzle )
[genreIds] => Array ( [0] => 6014 [1] => 7012 )
[releaseDate] => 2014-06-11T12:53:03Z
[sellerName] => Fabsys Technologies Private Limited
[bundleId] => com.quicksailor.EscapeUtilityRoom
[trackId] => 885565970
[trackName] => Escape Utility Room
[primaryGenreName] => Games
[primaryGenreId] => 6014
[minimumOsVersion] => 4.3
[formattedPrice] => Free
[wrapperType] => software
[trackCensoredName] => Escape Utility Room
[trackViewUrl] => https://itunes.apple.com/us/app/escape-utility-room/id885565970?mt=8&uo=4
[contentAdvisoryRating] => 4+
[artworkUrl100] => http://a1367.phobos.apple.com/us/r30/Purple2/v4/05/73/db/0573db7e-967a-08af-5804-0ecbb38bac77/mzl.tbuwotsy.png
[languageCodesISO2A] => Array ( [0] => EN )
[fileSizeBytes] => 11570404
[sellerUrl] => http://www.quicksailor.com
[averageUserRatingForCurrentVersion] => 3
[userRatingCountForCurrentVersion] => 2
[trackContentRating] => 4+
)
       [1] => Array (  )
)
)


PHP code for retrieve data from Apple itunes


<?php $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2"); $json = json_decode($content, true); //print_R($json); $count=count($json); echo'<table><th>Name</th><th>Link</th><th>Image</th><th>Description</th>'; for($i=0;$i<$count;$i++) { echo'<tr><td>'.$json['results'][$i]['trackName'].'</td>'; echo'<td>'.$json['results'][$i]['trackViewUrl'].'</td>'; $ur=$json['results'][$i]['artworkUrl512']; echo '<td><img src="'.$ur.'" width="150px"></td>'; echo'<td>'.$json['results'][$i]['description'].'</td>'; echo'</tr>'; } echo'</table>'; ?>


             Now you can get all details of app in your table. You can get any details as you want as from this PHP codes using array index represented above.

Get screenshot urls from Apple itunes using PHP


             You can get all details from itunes. You have 4 screenshot urls are avaiable in itunes for each game, 2 for screenshotUrls and another 2 for ipadScreenshotUrls. It is in array. So you want to know how to get those urls from json using PHP. The PHP script is below for that:

<?php
   $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2");
       $json = json_decode($content, true);
//print_R($json);
$count=count($json);
for($i=0;$i<$count;$i++)
{
echo $json['results'][$i]['trackName'].'<br>';
echo $json['results'][$i]['screenshotUrls'][0].'<br>';
echo $json['results'][$i]['screenshotUrls'][1].'<br>';
echo $json['results'][$i]['ipadScreenshotUrls'][0].'<br>';
echo $json['results'][$i]['ipadScreenshotUrls'][1].'<br>';
}
?>

              You display this reults on html img tag. Then you can get screenshot urls for a game. Just like below,

<img src="<?php $json['results'][$i]['screenshotUrls'][1]; ?>">


             Now you can get image from itunes,


Get app details from itunes using php

Get App rating from itunes using PHP

      
                   You can also get rating of each app from Apple itunes using PHP.


<?php
   $content=file_get_contents("https://itunes.apple.com/search?term=fabsys&country=us&entity=software&limit=2");
   $json = json_decode($content, true);
   //print_R($json);
  $count=count($json);
  echo'<table><th>Name</th><th>Rating</th>';
  for($i=0;$i<$count;$i++)
 {
    echo'<tr><td>'.$json['results'][$i]['trackName'].'</td>';
    echo'<td>'.$json['results'][$i]['trackContentRating'].'</td>';
    echo'</tr>';
 }
 echo'</table>';
?>

8 Oct 2014

Parse / Retrieve data from json file using php

                       You know how to create JSON file using PHP. Then we are going know how to get data from json file.

                       That means,  The json file returns encoded values. You have to decode it to display at wherever you wants. You can get data string from JSON using php.

                       The JSON file returns value as an array format, object format or combined both. See my previous post How to create JSON file using PHP.
                       In previous post, It give output like this:

       [    
           {
              'tutorial':'PHP',
              'link':'http://www.phponwebsites.com/p/php.html'
           },
           {
              'tutorial':'Mysql',
              'link':'http://www.phponwebsites.com/p/mysql.html'
           },
           {
            'tutorial':'htaccess',
            'link':'http://www.phponwebsites.com/p/htaccess.html'
           }    
      ]

Get data from JSON file using curl in PHP


               Now, you retrieve data from JSON file using PHP. Consider the following PHP script for retrieve data from JSON file.

  <?php

    $ch = curl_init("http://www.phponwebsites.com/json.php"); // add your url which contains json file
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($content, true);
    //print_R($json);
    $count=count($json);
    echo'<table><th>Tutorial</th><th>Link</th>';
    for($i=0;$i<$count;$i++)
    {
      echo'<tr><td>'.$json[$i]['tutorial'].'</td><td>'.$json[$i]['url'].'</td></tr>';
    }
    echo'</table>';

?>

      where,
                  json_decode() - takes JSON encoded values and converts it to PHP variable
If you want to know about cURL, then visit php.net

Get data from JSON file using file_get_contents in PHP



 <?php
    $content=file_get_contents("http://www.phponwebsites.com/json-api.php");  // add your url which contains json file
    $json = json_decode($content, true);
   // print_R($json);
    $count=count($json);
    echo'<table><th>Tutorial</th><th>Link</th>';
    for($i=0;$i<$count;$i++)
    {
      echo'<tr><td>'.$json[$i]['tutorial'].'</td><td>'.$json[$i]['url'].'</td></tr>';
    }
   echo'</table>';
  ?>

           
       where,
                   file_get_contents() - reads whole values in file into a string

              When you print_r() the results, you will get output like this:

Array (
         [0] => Array ( [PHP] => Differences The Ranch House
                               [link] => http://www.phponwebsites.com/p/php.html
                             )
         [1] => Array ( [Mysql] => Kids Bus Kiss
                               [link] => http://www.phponwebsites.com/p/mysql.html
                            )
         [2] => Array ( [htaccess] => Beehive Hideout
                                [link] => http://www.phponwebsites.com/p/htaccess.html
                           )
          )

Finally, you will get output like this:

TutorialLink
PHPhttp://www.phponwebsites.com/p/php.html
Mysqlhttp://www.phponwebsites.com/p/mysql.html
htaccesshttp://www.phponwebsites.com/p/htaccess.html


Related Post:
Create XML file using PHP and MySQL
Create Excel file using PHP and MySQL
Create Sitemap using PHP and MySQL
Create RSS Feed using PHP and MySQL
Get / Parse data from XML Sitemap using PHP
Read data from RSS Feed using PHP
Parse data from XML file using PHP

21 Aug 2014

Create json file using PHP and MySQL

                        You can create json file using PHP and Mysql. You can get output as json format using PHP and Mysql. Before you want to know that, first you should know what is json? and what is the us of json?

JSON

      
                       JSON expands JavaScript Object Notation. It is one of the data interchange format. You can easily read and write data through JSON file.
                       It is language independent. So you can retrieve data from it using any familiar languages like PHP. It should be array format, object format and both array and object fotmat.
     The array format of Json file should be like this,

       [    
           {
              'tutorial':'PHP',
              'link':'http://www.phponwebsites.com/p/php.html'
           },
           {
              'tutorial':'Mysql',
              'link':'http://www.phponwebsites.com/p/mysql.html'
           },
           {
            'tutorial':'htaccess',
            'link':'http://www.phponwebsites.com/p/htaccess.html'
           }    
      ]

The object of JSON should be like this,

    {  
           'tutorial':'PHP',
            'link':'http://www.phponwebsites.com/p/php.html'  
    }

Get output as json format using PHP and Mysql


                           Now you know something about JSON files. So we are going to know how to get output as JSON format using php and mysql.

Add header to create json file using PHP and Mysql

       
                          If you want to create json file, then you have to add header for json file. It is like below

header('Content-Type: application/json'); 

          Where json indicate this is json file

Add content to json file using PHP


             Then you need to add contents to your json file as you want as. Retrieve values from query result using mysql_fetch_arraySuppose you have more values in a variable. Then you need to store all values in array. Consider the following PHP code.

<?php
header('Content-Type: application/json');
$linklist=array();
$link=array();
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('quicksai_quick') or die(mysql_error());
$qr=mysql_query("SELECT * FROM `links` ") or die(mysql_error());
while($res=mysql_fetch_array($qr))
{
 $link['tutorial']=$res['tutorial'];
 $link['url']=$res['url'];
 array_push($linklist,$link);
}
//print_R($linklist);
echo json_encode($linklist);
?>

      The above example explain how to create json file on multidimensional array using PHP and Mysql.
     where,
               array() - create array variable.
               array_push() - insert values into array
               json_encode() - encode the values and returns JSON representation of values
             

The above example will give output as json file. It should be like this:
      
      [
      {'tutorial':'PHP', 'link':'http://www.phponwebsites.com/p/php.html'},
      {'tutorial':'Mysql', 'link':'http://www.phponwebsites.com/p/mysql.html'},
      {'tutorial':'htaccess','link':'http://www.phponwebsites.com/p/htaccess.html'}
      ]