Bitcoin Forum

Bitcoin => Project Development => Topic started by: Mageant on October 18, 2011, 09:27:59 PM



Title: PHP code for current Bitcoin price on your website
Post by: Mageant on October 18, 2011, 09:27:59 PM
Here is some PHP code I wrote for my website which pulls the current Bitcoin price from bitcoincharts and stores it in a table (change the currency variable in the beginning to the currency you wish to have):

Code:
<?php
/**
*
* @package Bitcoin Price MOD
* @author Channing Jones
* @version 1.0.0
* @copyright (c) 2011 Channing Jones
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

include('config.php');
$currency "EUR";

$conn mysql_connect($dbhost$dbuser$dbpasswd) or die('Error connecting to mysql');
mysql_select_db($dbname$conn);

$result mysql_query("SELECT * FROM bitcoin_price WHERE id_currency='$currency'");

while(
$row mysql_fetch_array($result))
  {
  
$last_updated $row['dt_updated']; // the date & time this record was last updated
  
$current_date date('Y-m-d H:i:s'); // the current date & time

  
$d_start  = new DateTime($last_updated);
  
$d_end    = new DateTime($current_date);
  
$diff  = date_diff($d_start$d_end);
  
  if (
$diff->y>or $diff->m>or $diff->d>or $diff->h>=1// at least one hour difference since last url call
    
{
    
// get the new price from bitcoin charts
$ch curl_init(); 
curl_setopt($chCURLOPT_URL'http://bitcoincharts.com/t/weighted_prices.json'); 
curl_setopt($chCURLOPT_HEADER1); 
curl_setopt($chCURLOPT_RETURNTRANSFER1); 
$file_contents strstr(curl_exec($ch),'{'); // get everything starting from first curly bracket
curl_close($ch); 

    if (
$file_contents)
      {
      
$currency_data json_decode($file_contentsTRUE);
      
$price $currency_data[$currency]['24h']; // get the 24h-average price
  $sql "UPDATE bitcoin_price SET dd_price=$price, dt_updated='$current_date' WHERE id_currency='$currency'"// store this value in the table for fast recall
  mysql_query($sql);
  }
    else
      {
  
  echo('Error getting json file');
  
  }   
    }
  else
    {
    
$price $row['dd_price'];   
    }

  }
  
$price_formatted number_format($price,4,',','.'); // german number format with 4 digits after the decimal point
echo "$price_formatted $currency";  

mysql_close($conn);
?>

Here is the SQL statement to create the appropriate table:
Code:
--
-- table structure `bitcoin_price`
--

CREATE TABLE IF NOT EXISTS `bitcoin_price` (
  `id_currency` char(3) CHARACTER SET latin1 COLLATE latin1_german1_ci NOT NULL,
  `dd_price` double NOT NULL,
  `dt_updated` datetime NOT NULL,
  PRIMARY KEY (`id_currency`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- example data `bitcoin_price`
--

INSERT INTO `bitcoin_price` (`id_currency`, `dd_price`, `dt_updated`) VALUES
('EUR', 2.1471, '2011-10-18 23:14:00');


Title: Re: PHP code for current Bitcoin price on your website
Post by: Xenland on November 02, 2011, 08:31:06 PM
I'll be adding this as a Module to BitcoinRetail-Lite thanks this is great out of the box working code(by out of the box i mean PHP5-curl already installed:P)


Title: Re: PHP code for current Bitcoin price on your website
Post by: vv01f on November 02, 2011, 09:13:38 PM
Probably its nicer to form a class of the subject, could make inclusion in CMS/Websites more easy.

just a snippet to avoid incompatibility with older php-versions via some fallback
Code:
if(function_exists('json_decode')){
$currency_data = json_decode($file_contents, true);
}else{
$currency_data = /*$this->*/fromJSON($file_contents, true);
}

curl is an option, heres another one:
Code:
$file_contents = @file_get_contents("http://bitcoincharts.com/t/markets.json");

And the code of a alternative parser..
Code:
/*
  simplejson - a tiny JSON parser for older PHP versions
  ------------
  The main purpose of this is to allow the parsing of JSON encoded strings
  into PHP native structures, or PHP objects encoding into JSON strings.
  Primary target for this are mature systems running versions of PHP older
  than 5.2, which provides this functionality.
  
  The functions are confirmed to work on PHP as old as 4.1.2.
  
  The functions do not care about character encoding and will do nothing
  to magically fix character set issues. They'll work with the data
  as-provided and won't, for example, (un)escape \u0000 or \x00 characters.
  
  WARNING: Be aware that the string input is being "evaluated" and run by this
  function with all the implications that includes!
  
  ------------
  
  Copyright (C) 2006 Borgar Thorsteinsson [borgar.undraland.com]
  
  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
  ------------
 * Parses a JSON string into a PHP variable.
 * @param string $json  The JSON string to be parsed.
 * @param bool $assoc   Optional flag to force all objects into associative arrays.
 * @return mixed        Parsed structure as object or array, or null on parser failure.
 */
function fromJSON ( $json, $assoc = false ) {
  /* by default we don't tolerate ' as string delimiters
     if you need this, then simply change the comments on
     the following lines: */
  // $matchString = '/(".*?(?<!\\\\)"|\'.*?(?<!\\\\)\')/';
  $matchString = '/".*?(?<!\\\\)"/';
  
  // safety / validity test
  $t = preg_replace( $matchString, '', $json );
  $t = preg_replace( '/[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/', '', $t );
  if ($t != '') { return null; }

  // build to/from hashes for all strings in the structure
  $s2m = array();
  $m2s = array();
  preg_match_all( $matchString, $json, $m );
  foreach ($m[0] as $s) {
    $hash       = '"' . md5( $s ) . '"';
    $s2m[$s]    = $hash;
    $m2s[$hash] = str_replace( '$', '\$', $s );  // prevent $ magic
  }
  
  // hide the strings
  $json = strtr( $json, $s2m );
  
  // convert JS notation to PHP notation
  $a = ($assoc) ? '' : '(object) ';
  $json = strtr( $json,
    array(
      ':' => '=>',
      '[' => 'array(',
      '{' => "{$a}array(",
      ']' => ')',
      '}' => ')'
    )
  );
  
  // remove leading zeros to prevent incorrect type casting
  $json = preg_replace( '~([\s\(,>])(-?)0~', '$1$2', $json );
  
  // return the strings
  $json = strtr( $json, $m2s );

  /* "eval" string and return results.
     As there is no try statement in PHP4, the trick here
     is to suppress any parser errors while a function is
     built and then run the function if it got made. */
  $f = @create_function( '', "return {$json};" );
  $r = ($f) ? $f() : null;

  // free mem (shouldn't really be needed, but it's polite)
  unset( $s2m ); unset( $m2s ); unset( $f );

  return $r;
}

/**
 * Encodes a PHP variable into a JSON string.
 * @param mixed $value A PHP variable to be encoded.
 */
function toJSON ( $value ) {

  if ($value === null) { return 'null'; };  // gettype fails on null?

  $out = '';
  $esc = "\"\\/\n\r\t" . chr( 8 ) . chr( 12 );  // escaped chars
  $l   = '.';  // decimal point
  
  switch ( gettype( $value ) )
  {
    case 'boolean':
      $out .= $value ? 'true' : 'false';
      break;
      
    case 'float':
    case 'double':
      // PHP uses the decimal point of the current locale but JSON expects %x2E
      $l = localeconv();
      $l = $l['decimal_point'];
      // fallthrough...

    case 'integer':
      $out .= str_replace( $l, '.', $value );  // what, no getlocale?
      break;

    case 'array':
      // if array only has numeric keys, and is sequential... ?
      for ($i = 0; ($i < count( $value ) && isset( $value[$i]) ); $i++);
      if ($i === count($value)) {
        // it's a "true" array... or close enough
        $out .= '[' . implode(',', array_map('toJSON', $value)) . ']';
        break;
      }
      // fallthrough to object for associative arrays...

    case 'object':
      $arr = is_object($value) ? get_object_vars($value) : $value;
      $b = array();
      foreach ($arr as $k => $v) {
        $b[] = '"' . addcslashes($k, $esc) . '":' . toJSON($v);
      }
      $out .= '{' . implode( ',', $b ) . '}';
      break;

    default:  // anything else is treated as a string
      return '"' . addcslashes($value, $esc) . '"';
      break;
  }
  return $out;
  
}


Title: Re: PHP code for current Bitcoin price on your website
Post by: jon@bitcoinads.com on August 26, 2014, 04:02:39 AM
What the heck?

I can hit the api with a browser get request but...

php:
file_get_contents('http://api.bitcoincharts.com/v1/weighted_prices.json');

or

terminal:
curl http://bitcoincharts.com/t/weighted_prices.json

are not able to connect.

What am I missing?


Title: Re: PHP code for current Bitcoin price on your website
Post by: vv01f on August 26, 2014, 07:39:58 AM
What the heck?
tl;dr: it works if you do it right, keep trying.

0. take advantage of documentation: http://bitcoincharts.com/about/markets-api/
1. there is no version 't'
2. the answer if you request version 't' is 404
3. if you read curl manual you'd know that it takes its time if you don't limit it
4. your browser might give more pleasant information to the server about himself than curl does, although this is no problem at bitcoincharts.com - so watch what you are sending there

btw: you should never rely on a single source only, try to fetch more

have fun ;)


Title: Re: PHP code for current Bitcoin price on your website
Post by: Bitsky on August 26, 2014, 06:01:21 PM
file_get_contents('http://api.bitcoincharts.com/v1/weighted_prices.json');
If you're running a distro with SELinux, you need to set the boolean for httpd_can_network_connect to on

curl http://bitcoincharts.com/t/weighted_prices.json
This ends in a 404. Use -I to check return codes.