Skip to content

PHP Example Code

MMDRZA edited this page Oct 18, 2024 · 1 revision

PHP Fetching from a JSON Free API

PHP Fetching Cryptocurrency Data (Price / Rate) from a JSON Free API

This section demonstrates how to fetch and display cryptocurrency data from a remote JSON file using PHP. The example below retrieves information such as symbol, last price, 24-hour high and low prices, change rate, and last updated timestamp for various coins. The data source is provided in the form of a raw JSON file hosted on GitHub.

PHP Example Code

<?php

// URL of the raw JSON file
$raw_json_url = "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json";

/**
 * Fetch JSON data from a given URL.
 *
 * @param string $url The URL of the JSON resource.
 * @return array|null Returns an associative array containing the JSON data, or null on failure.
 */
function fetch_json_data($url) {
    $options = [
        "http" => [
            "method" => "GET",
            "header" => "User-Agent: PHP"
        ]
    ];
    $context = stream_context_create($options);

    // Make the request
    $response = @file_get_contents($url, false, $context);

    if ($response === FALSE) {
        throw new Exception("Failed to retrieve data from $url.");
    }

    // Decode the JSON response
    $json_data = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception("Error parsing JSON: " . json_last_error_msg());
    }

    return $json_data;
}

/**
 * Display information about a cryptocurrency coin.
 *
 * @param array $coin_data An associative array containing information about a coin.
 */
function display_coin_info($coin_data) {
    if (!isset($coin_data['symbol'], $coin_data['lastPrice'], $coin_data['highPrice24h'], $coin_data['lowPrice24h'], $coin_data['changeRate'], $coin_data['lastUpdated'])) {
        throw new Exception("Missing expected key(s) in data.");
    }

    // Extracting the coin information
    $symbol = $coin_data['symbol'];
    $last_price = $coin_data['lastPrice'];
    $high_price_24h = $coin_data['highPrice24h'];
    $low_price_24h = $coin_data['lowPrice24h'];
    $change_rate = $coin_data['changeRate'];
    $last_updated = $coin_data['lastUpdated'];

    // Print the formatted coin information
    echo "Symbol: $symbol | LAST: $last_price | HIGH: $high_price_24h | LOW: $low_price_24h | CHANGE: $change_rate | UPDATED: $last_updated\n";
}

// Main execution block
try {
    // Fetch the JSON data from the given URL
    $coin_data_list = fetch_json_data($raw_json_url);

    // Loop through each coin's data and display its information
    foreach ($coin_data_list as $coin) {
        display_coin_info($coin);
    }
} catch (Exception $e) {
    // Handle exceptions and print the error message
    echo "Error: " . $e->getMessage() . "\n";
}
?>

How It Works:

Fetching Data: The fetch_json_data function sends an HTTP GET request to the provided URL using file_get_contents. It sets a User-Agent header to mimic a browser-like request, ensuring better compatibility with some web servers. The JSON data is then parsed into an associative array using json_decode. If there are any issues with retrieving or parsing the data, the function throws an exception.

Displaying Coin Information: The display_coin_info function takes an associative array containing the coin's data and prints it in a formatted manner. It checks for the existence of required keys (symbol, lastPrice, etc.) before displaying the information.

Error Handling: The script includes basic error handling with try-catch blocks. If any exception is thrown during the fetching or displaying of data, the error message is printed to the console.

How to Use:

Run the Script: Save the PHP script and run it using the PHP CLI or through a web server. For CLI usage, run the following command:

php fetch_crypto_data.php

Example Output:

Symbol: BTC | LAST: 47000 | HIGH: 47200 | LOW: 46500 | CHANGE: 1.5% | UPDATED: 2024-10-15 12:34:56
Symbol: ETH | LAST: 3200 | HIGH: 3250 | LOW: 3150 | CHANGE: 2.0% | UPDATED: 2024-10-15 12:35:12

This script can be easily adapted and integrated into web applications, APIs, or cron jobs to fetch and display cryptocurrency data dynamically

Clone this wiki locally