api php code example

Example 1: external api php

<?php
function getServerStatistics($url) {
    $statisticsJson = file_get_contents($url);
    if ($statisticsJson === false) {
       return false;
    }

    $statisticsObj = json_decode($statisticsJson);
    if ($statisticsObj !== null) {
       return false;
    }

    return $statisticsObj;
}

// ...

$stats = getServerStatistics($url);
if ($stats !== false) {
    print $stats->players->online;
}

Example 2: web api return json example in php

$option = $_GET['option'];

if ( $option == 1 ) {
    $data = [ 'a', 'b', 'c' ];
    // will encode to JSON array: ["a","b","c"]
    // accessed as example in JavaScript like: result[1] (returns "b")
} else {
    $data = [ 'name' => 'God', 'age' => -1 ];
    // will encode to JSON object: {"name":"God","age":-1}  
    // accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}

header('Content-type: application/json');
echo json_encode( $data );

Example 3: rest api example php

CREATE TABLE `Transaction` (
  `id` int(11)  UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
  `comment` text,
  `price` float,
  `quantity` float,
  `reason` enum('New Stock','Usable Return','Unusable Return'),
  `createdAt` datetime NOT NULL,
  `updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `productid` int(11) NOT NULL
);

Tags:

Sql Example