/** * Возвращает json_decode ответ от метрики * @param string $method Тип_метода ― GET, POST, PUT или DELETE. * @param string $path Имя_метода ― URL ресурса, над которым выполняется действие. * @param array $options Параметры ― Обязательные и необязательные параметры запроса, которые не входят в состав URL ресурса. */ private function QueryYandex($method = "get", $path = "/counters", $options = array()) { $opt = ""; if ($method === "get") { foreach ($options as $key => $value) { if ($value != null) { $opt .= "{$key}={$value}&"; } } $ret = Unirest\Request::get("http://api-metrika.yandex.ru" . $path . ".json?pretty=1&{$opt}", array("Content-Type" => "application/x-yametrika+json", "Authorization" => "OAuth " . $this->access_token, "Accept" => "application/x-yametrika+json")); } else { $ret = Unirest\Request::$method("http://api-metrika.yandex.ru" . $path . ".json?pretty=1", array("Content-Type" => "application/x-yametrika+json", "Authorization" => "OAuth " . $this->access_token, "Accept" => "application/x-yametrika+json", json_encode($options))); } if ($ret->code != 200) { if (property_exists(json_decode($ret->raw_body), 'errors')) { $errors = $ret->body->errors; foreach ($errors as $err) { throw new Exception("Error:: " . "[" . $err->code . "] [" . $this->error_code[$err->code] . "]"); } } } elseif (property_exists(json_decode($ret->raw_body), 'errors')) { $errors = $ret->body->errors; foreach ($errors as $err) { throw new Exception("Method error:: " . "[" . $err->code . "] [" . $err->text . "]"); } } else { return json_decode($ret->raw_body); } }
function webhookCallback() { global $connectHost, $requestHeaders; if ($_SERVER['REQUEST_METHOD'] == 'POST') { # Get the JSON body and HMAC-SHA1 signature of the incoming POST request $callbackBody = file_get_contents('php://input'); $callbackSignature = getallheaders()['X-Square-Signature']; # Validate the signature if (!isValidCallback($callbackBody, $callbackSignature)) { # Fail if the signature is invalid error_log("Webhook event with invalid signature detected!"); return; } # Load the JSON body into an associative array $callbackBodyJson = json_decode($callbackBody); # If the notification indicates a PAYMENT_UPDATED event... if (property_exists($callbackBodyJson, 'event_type') and $callbackBodyJson->event_type == 'PAYMENT_UPDATED') { # Get the ID of the updated payment $paymentId = $callbackBodyJson->entity_id; # Send a request to the Retrieve Payment endpoint to get the updated payment's full details $response = Unirest\Request::get($connectHost . '/v1/me/payments/' . $paymentId, $requestHeaders); # Perform an action based on the returned payment (in this case, simply log it) error_log(json_encode($response->body, JSON_PRETTY_PRINT)); } } else { error_log("Received a non-POST request"); } }
public function get($url) { Unirest\Request::auth($this->login, $this->pass); Unirest\Request::defaultHeader('User-Agent', $this->service . " (" . $this->mail . ")"); $response = Unirest\Request::get($this->root . $url . '.json'); if (floor($response->code / 100) >= 4) { throw new Error($response->body->errors->error[0]); } return $response->body; }
function getChapter($siteId, $mangaId, $chapterId) { $url = "https://doodle-manga-scraper.p.mashape.com/" . $siteId . "/manga/" . $mangaId . "/" . $chapterId; $response = Unirest\Request::get($url, array("X-Mashape-Key" => "S4X6YXGRxxmshLDxygnESvTmQ3kAp1DSsDDjsnx14NHnev0ocV", "Accept" => "text/plain")); $responseBody = $response->body; $chapter[0] = $responseBody->name; foreach ($responseBody->pages as $page) { $chapter[$page->pageId] = $page->url; } return $chapter; }
function addCustomGame($postName, $postGenre = "", $postMetacritic = "", $postTimetobeat = "") { $servername = "localhost:3306"; $username = "******"; $password = ""; $dbname = "steamgames"; $nameString = $postName; $type = "game"; $genreString = $postGenre; $header_image = ""; $metacritic = $postMetacritic; $recommendations = "manually added"; $timetobeat = $this->getDataFromHowlongtobeat($nameString); if (strcmp($timetobeat, "no info")) { $timetobeat = $postTimetobeat; } if (!$this->checkDatabaseByName($nameString)) { $response = Unirest\Request::get("https://ahmedakhan-game-review-information-v1.p.mashape.com/api/v1/information?game_name=" . $nameString, array("X-Mashape-Key" => "QyibUbgQ9zmshV0vBfcODcQk9x8yp1L7QdkjsnDlchW0tBoziv", "Accept" => "application/json")); print_r($response); if ($response->code == "200") { $json = $response->raw_body; $obj = json_decode($json, true); if (array_key_exists('result', $obj)) { $obj = $obj['result']; $genreString = ""; foreach ($obj['genre'] as $genre) { $genreString .= $genre . ", "; } $genreString = substr($genreString, 0, strlen($genreString) - 2); $header_image = $obj['thumbnail']; $metacritic = $obj['metacritic']['criticScore']; } } $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO games (name, type, header_image, genres, recommendations, timetobeat, metacritic, played, appid)\n VALUES ('" . $nameString . "', '" . $type . "', '" . $header_image . "', '" . $genreString . "', '" . $recommendations . "', '" . $timetobeat . "', '" . $metacritic . "', 'no'," . rand(1000000, 10000000) . ")"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); } else { echo "already in database"; } }
/** * Use the selectors to retrieve a number of objects. * * @param One_Scheme $scheme * @param array $selectors * @return array */ public function select(&$scheme, $selectors) { // if (count($selectors)) { // foreach ($selectors as $sel) { // list($path, $val, $op) = $sel; // $query->where($path, $op, $val); // } // } $this->init($scheme); $route = $this->map->selectRoute; $response = Unirest\Request::get($route); print_r($response); // $selection = $this->executeSchemeQuery($query); // return (count($selection) > 0) ? $selection : NULL; }
function get2014Payments() { global $accessToken, $connectHost; # Restrict the request to the 2014 calendar year, eight hours behind UTC # Make sure to URL-encode all parameters $parameters = http_build_query(array('begin_time' => '2014-01-01T00:00:00-08:00', 'end_time' => '2015-01-01T00:00:00-08:00')); # Standard HTTP headers for every Connect API request $requestHeaders = array('Authorization' => 'Bearer ' . $accessToken, 'Accept' => 'application/json', 'Content-Type' => 'application/json'); $payments = array(); $requestPath = $connectHost . '/v1/me/payments?' . $parameters; $moreResults = true; while ($moreResults) { # Send a GET request to the List Payments endpoint $response = Unirest\Request::get($requestPath, $requestHeaders); # Read the converted JSON body into the cumulative array of results $payments = array_merge($payments, $response->body); # Check whether pagination information is included in a response header, indicating more results if (array_key_exists('Link', $response->headers)) { $paginationHeader = $response->headers['Link']; if (strpos($paginationHeader, "rel='next'") !== false) { # Extract the next batch URL from the header. # # Pagination headers have the following format: # <https://connect.squareup.com/v1/MERCHANT_ID/payments?batch_token=BATCH_TOKEN>;rel='next' # This line extracts the URL from the angle brackets surrounding it. $requestPath = explode('>', explode('<', $paginationHeader)[1])[0]; } else { $moreResults = false; } } else { $moreResults = false; } } # Remove potential duplicate values from the list of payments $seenPaymentIds = array(); $uniquePayments = array(); foreach ($payments as $payment) { if (array_key_exists($payment->id, $seenPaymentIds)) { continue; } $seenPaymentIds[$payment->id] = true; array_push($uniquePayments, $payment); } return $uniquePayments; }
function getTrends($index, $section) { global $host; global $apiKey; global $all_sections; // $request = "http://api.chartbeat.com/live/toppages/v3/?apikey={$apiKey}&host={$host}§ion={$section}&limit=100"; // $response = Unirest\Request::get($request, array("Accept" => "application/json")); // $json = $response->raw_body; // $arr = json_decode($json); // $data = $arr->pages; //echo var_dump($data); foreach ($data as $key => $value) { if ($value->authors != NULL) { // array_push($all_sections[$index], getSlug($value->path)); } } }
public function Countries() { // get data from $headers = array(); $body = array('username' => Public_Api_Username, 'password' => Public_Api_Password, 'action' => 'get_country', 'gzip' => 'no'); $response = Unirest\Request::get(Public_Api_URl, $headers, $body); $items = json_decode($response->raw_body); $country = array(); $temp = array(); for ($k = 0; $k <= 500; $k++) { $j = $k + 1; if (isset($items->{$j})) { $temp['index'] = $k; $temp['Code'] = $items->{$k}->Code; $temp['Name'] = $items->{$k}->Name; array_push($country, $temp); } else { //end for break; } } return $country; }
/** * Fetches a json containing a randomly generated word from the API, based on the difficulty * setting. Returns the json. * @param unknown $url */ private function retrieveRandomWord($url) { $response = Unirest\Request::get($url, array("X-Mashape-Key" => "xJkqXGguDTmshoNIaGVnrMZlFPmUp1WrnZLjsn8DDx3DFQhNq5", "Accept" => "application/json")); $wordJSON = json_decode($response->raw_body); $word = $wordJSON->{"word"}; /* * The API provides some weird words (if you can even call them that) like "dr. j" which I don't think should be included. * If such a word is provided, the function instead calls itself recursively to get a new word. */ if (strpos($word, '.') !== false || strpos($word, ' ') !== false) { return retrieveRandomWord($url); } else { return strtoupper($word); } /*Loose idea for discarding words with too low frequency. API seems to be broken however, * sometimes the frequency parameter doesn't exist, unsure of the cause (nothing stated in docs). * * * $freq = $wordJSON->{"frequency"}; * if ($freq > 3.5) return $wordJSON->{"word"}; * else return retrieveRandomWord($url); */ }
public function ReadHotels($params) { $headers = array(); $params['action'] = 'hotel_search'; $params['username'] = Public_Api_Username; $params['password'] = Public_Api_Password; try { $response = Unirest\Request::get(Public_Api_URl, $headers, $params); $items = json_decode($response->raw_body); } catch (Exception $ex) { $items = array(); } //save items as array if ($items->TotalCount) { $hotels = array(); foreach ($items->TotalCount as $h) { array_push($hotels, $h); } //svae items in dbase return $hotels; } else { return array(); } }
exit; }); $app->get('/api/v1/zip/:zip', function ($zip) { $headers = array("Accept" => "application/json"); $key = '2f4d666f6f04dbad2164175736a5a2dc'; $url = "http://api.openweathermap.org/data/2.5/weather?zip={$zip}&APPID={$key}&units=imperial"; $response = Unirest\Request::get($url, $headers); header("Content-Type: application/json"); echo json_encode($response->body); exit; }); $app->get('/api/v1/forecast/:lat/:lon', function ($lat, $lon) { $headers = array("Accept" => "application/json"); $key = '2f4d666f6f04dbad2164175736a5a2dc'; $url = "http://api.openweathermap.org/data/2.5/forecast/daily?lat={$lat}&lon={$lon}&appid={$key}&units=imperial"; $response = Unirest\Request::get($url, $headers); header("Content-Type: application/json"); echo json_encode($response->body); exit; }); $app->get('/api/v1/loc/:zip', function ($zip) { $headers = array("Accept" => "application/json"); $url = "http://maps.googleapis.com/maps/api/geocode/json?address={$zip}"; $response = Unirest\Request::get($url, $headers); $resp = $response->body->results[0]->geometry->location; $res = array('lat' => $resp->lat, 'lon' => $resp->lng); header("Content-Type: application/json"); echo json_encode($res); exit; }); $app->run();
echo "<i class=\"fa fa-star evo-green\"></i>"; } ?> </div> <div> <?php echo "<a href=\"mailto:" . $obj['TaskOwnerEmailAddress'] . "?subject=" . $campaignName . " - " . $obj['TaskName'] . "&body=http://unilever.humanig.com/campaign/" . $project_id . "/" . $task_id . "\">"; ?> <div class="circle_container"><div class="email_address"><i class="fa fa-envelope-o"></i></div></div></a> </div> <?php $user_id = $obj['TaskOwnerUserID']; $url = $this->container->getParameter('apiUrl') . "users/" . $user_id . "/profile.json"; $api_key = $_COOKIE['api']; $api_header = array('x-wsse' => 'ApiKey="' . $api_key . '"'); $response = Unirest\Request::get($url, $api_header); $user_profile = json_decode($response->raw_body, true)[0]; $honey_id = $user_profile['honey_id']; $honey_link = "https://honey.is/home/#user/{$honey_id}/profile"; if ($honey_id) { echo '<div><a href="' . $honey_link . '"><div class="circle_container circle-honey"><div class="email_address"><i class="honey-link"></i></div></div></a><div>'; } ?> </th> </tr> </thead> <?php } ?> <tbody> <tr class="data_row">
public function getItems($options) { $headers = array('Cookie' => $this->webCookies, 'Timeout' => Unirest\Request::timeout(5)); $response = Unirest\Request::get('https://steamcommunity.com/trade/' . $options['tradeId'] . '/receipt/', $headers); if ($response->code != 200) { die('Error get items. Server response code: ' . $response->code); } $body = $response->body; preg_match('/(var oItem;[\\s\\S]*)<\\/script>/', $body, $matches); if (!$matches) { die('Error get items: no session'); } $temp = str_replace(array("\r", "\n"), "", $matches[1]); $items = array(); preg_match_all('/oItem = {(.*?)};/', $temp, $matches); foreach ($matches[0] as $key => $value) { $value = rtrim(str_replace('oItem = ', '', $value), ';'); $items[] = json_decode($value, 1); } return $items; }
<!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </head> <body> <form name="input" action="index.php" method="POST"> <div class="input-group"> <span class="input-group-btn"> <input type="submit" type="button">IR!</button> </span> <input type="text" name="word" class="form-control" placeholder="search for..."> </div> </form> <?php require __DIR__ . '/vendor/autoload.php'; $response = Unirest\Request::get("https://montanaflynn-dictionary.p.mashape.com/define?word=" . $_GET["word"], array("X-Mashape-Key" => "ZA8k3CJvxdmshT0XPS3S6WV6vnfwp1hj5F9jsnNujBw5cKjh2Y", "Accept" => "application/json")); echo "<ul class=\"nav nav-pills\">"; foreach ($response->body->definitions as $definition) { echo "<li role=\"presentation\"><a href=\"#\">" . $definition->text . "</a></li>"; } echo "</ul>"; ?> </div> </div> </body> </html>
<?php require_once 'unirest-php-master/src/Unirest.php'; // These code snippets use an open-source library. $request = Unirest\Request::get("https://itunes.apple.com/search?term=metallica", array("Accept" => "application/json")); echo "<pre>"; $output = "<ul>"; foreach ($request->body->results as $data) { print_r($data); /* $output .= "<h4>".$data['id']."</h4>"; $output .= "<h5>".$data['title']."</h5>"; $output .= "<li>Meal: ".$data['imageUrls']."</li>"; $output .= "<a href=>".$data['image']."</a>"; */ } $output .= "</ul>"; echo utf8_decode($output); ?>
<?php require_once 'C:\\xampp\\htdocs\\tb\\unirest-php-master\\src\\Unirest.php'; include 'core/init.php'; include 'includes/overall/header_loggedin.php'; // Unirest\Request::proxy('172.31.1.3', 8080, CURLPROXY_HTTP); // Unirest\Request::proxyAuth('iec2012075', ''); // $ch = curl_init("http://iiita.ac.in"); // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = Unirest\Request::get("https://site2sms.p.mashape.com/index.php?msg=bolyaarsushant&phone=7275065468&pwd=sushant&uid=7275065468", array("X-Mashape-Key" => "2AMQ553BWimshuYmDk9khdX7gKlKp1SUNzujsnbQkwxgQv2FyS", "Accept" => "application/json"));
<?php require_once 'unirest/Unirest.php'; $root = realpath($_SERVER["DOCUMENT_ROOT"]); // download all pdfs to a location // (use common code from the aggregator) // convert each PDF to an image // These code snippets use an open-source library. /*$response = Unirest\Request::post("https://pdf2jpg-pdf2jpg.p.mashape.com/convert_pdf_to_jpg.php", array( "X-Mashape-Key" => "4vQThd6WoJmshrauqDPfPu1tlWvvp1g826MjsnxIB4i4LNPhaf" ), array( "pdf" => Unirest\file::add(getcwd() . "/boc.pdf"), "resolution" => 150 ) );*/ $response = Unirest\Request::post("http://mockbin.org/bin/800a818b-5fb6-40d4-a342-75a1fb8599db?foo=bar&foo=baz", array("X-Mashape-Key" => "4vQThd6WoJmshrauqDPfPu1tlWvvp1g826MjsnxIB4i4LNPhaf"), array("pdf" => Unirest\Request::get("http://www.le-pinocchio.ch/view/data/3070/Menu%20de%20la%20semaine%202015.pdf"), "resolution" => 150)); if ($response->code == 200) { echo $response->body[0]->color; } else { echo 'error while converting'; }
/** * Execute GET request to Seats.io RESTful API * Full response in $this->response * @see Unirest for PHP http://unirest.io/php.html * * @param string $url endpoint URL * @return mixed Data - body of response * * @throws exceptionclass Throws exception when HTTP response is not 200 * * @access private */ private function getRequest($url = null) { if (!empty($url)) { $this->request->url = $url; } $this->request->data = null; $this->response = Unirest\Request::get($this->request->url, $this->request->headers); if ($this->response->code !== 200) { throw new Exception('getRequest - Exception: ' . (!empty($this->response->body) ? $this->response->body : implode("\n", $this->response->headers))); } return $this->response->body; }
<?php $this->load->view('/unirest/src/Unirest.php'); $response = Unirest\Request::get("https://omgvamp-hearthstone-v1.p.mashape.com/cards", array("X-Mashape-Key" => "h1qylTCmitmshxurlWa9zZuVvvb5p10IB58jsnIYzfQeooEdLv", "Accept" => "json")); // var_dump( $response->body->Basic); $query_str = ""; for ($i = 0; $i < count($response->body->Basic); $i++) { $name = $response->body->Basic[$i]->name; $api_id = $response->body->Basic[$i]->cardId; $cardSet = $response->body->Basic[$i]->cardSet; $type = $response->body->Basic[$i]->type; if (isset($response->body->Basic[$i]->artist)) { $artist = $response->body->Basic[$i]->artist; } else { $artist = 'null'; } if (isset($response->body->Basic[$i]->faction)) { $faction = $response->body->Basic[$i]->faction; } else { $faction = 'null'; } if (isset($response->body->Basic[$i]->collectible)) { $collectible = "YES"; } else { $collectible = "NO"; } if (isset($response->body->Basic[$i]->playerClass)) { $playerClass = $response->body->Basic[$i]->playerClass; } else { $playerClass = 'null'; }
<?php include "vendor/autoload.php"; include "/databaseConnect/databaseConnectionFoodSearch.php"; Unirest\Request::verifyPeer(false); // These code snippets use an open-source library. $response = Unirest\Request::get("https://nutritionix-api.p.mashape.com/v1_1/search/{urlencode({$_POST['item_name']})}?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat", array("X-Mashape-Key" => "XU83D7WqBomshL1uFNq7KVvGMz8Wp1IGNqzjsnUgU0fQWqPRk1", "Accept" => "application/json")); ?> <html> <!-- BEGIN HTML --> <body> <div class="row panel center"> <!-- FORM | food search API --> <h4>API Food Product Search</h4> <div id="form"> <form action="food_api.php" method="post"> <fieldset> <!-- ADDED RESET BUTTON --> <input type="reset" name="Reset" value="RESET" tabindex="6"> </fieldset> <fieldset> <label for="item_name">Search a Food Item:</label> <input type="search" name="item_name" id="item_name" value="" tabindex="1" required /> <input type="submit" name="submit" value="SUBMIT" tabindex="5" /> <br /> </fieldset> </form> </div> <?php
public function testGetArray() { $response = Unirest\Request::get('http://httpbin.org/get', array(), array( 'name[0]' => 'Mark', 'name[1]' => 'John' )); $this->assertEquals(200, $response->code); $args = $response->body->args; $this->assertEquals('Mark', $args->{'name[0]'}); $this->assertEquals('John', $args->{'name[1]'}); }
$fileUpload = '/Users/rimaraksa/Sites/android_connect' . '/' . $targetPath . $signature; // Change X-Mashape-Key, album, and album key $X_Mashape_Key = "yxgaLRvhf3msh8lKOCP4kiyng64Np1NlssnjsngXI6UmUTXXBN"; $album = "Approve"; $albumkey = "93047593e2f2fb8176be64548e998490f3ee24ec4ce7d091d7082eea18051c5d"; $url = "https://lambda-face-recognition.p.mashape.com/album_train"; // Train the album in Lambdal server $response = Unirest\Request::post($url, array("X-Mashape-Key" => $X_Mashape_Key), array("album" => $album, "albumkey" => $albumkey, "entryid" => $username, "files" => Unirest\File::add($fileUpload))); // Write the respose after training the album $file = fopen("log_album_train.txt", "w"); fwrite($file, $response->raw_body); fclose($file); // URL for rebuilding an album $url = "https://lambda-face-recognition.p.mashape.com/album_rebuild?album=" . $album . "&albumkey=" . $albumkey; // Rebuild the album in Lambdal server $response = Unirest\Request::get($url, array("X-Mashape-Key" => $X_Mashape_Key, "Accept" => "application/json")); // Write the respose from rebuilding the album $file = fopen("log_album_rebuild.txt", "w"); fwrite($file, $response->raw_body); fclose($file); // Prepare for returning the result to user // The file was not uploaded successfully to Lambal server if (!$response) { $account["signatureUploadFails"] = true; $account["exists"] = false; } else { $result = mysqli_query($con, "INSERT INTO accounts(name, nric, phone, username, password, profpic, signature) VALUES('{$name}', '{$nric}', '{$phone}', '{$username}', '{$password}', '{$profpic}', '{$signature}')"); $file = fopen("log_insert_account.txt", "w"); fwrite($file, $result); fclose($file); $account["exists"] = true;
$app->get('/pantryApp', function () use($app) { $app->render('pantryApp.twig'); }); $app->get('/recipeApp', function () use($app) { $app->render('recipeApp.twig'); $data = $response->body->hits; try { foreach ($data as $recipe) { echo '<li class="panel">' . "Label: " . $recipe->recipe->label . '<br>' . 'Source: ' . $recipe->recipe->source . '<br>' . $recipe->recipe->uri . '<br>' . $recipe->recipe->url . '</li>'; } } catch (Exception $e) { echo $e->getMessage(); } Unirest\Request::verifyPeer(false); // These code snippets use an open-source library. http://unirest.io/php $response = Unirest\Request::get("https://edamam-recipe-search-and-diet-v1.p.mashape.com/search?_app_id=691b076d&_app_key=3e8c229f325ab89e7d270b29c8294a35&q={$_POST['item_name']}", array("X-Mashape-Key" => "XU83D7WqBomshL1uFNq7KVvGMz8Wp1IGNqzjsnUgU0fQWqPRk1", "Accept" => "application/json")); }); //DATAENTRY FORM require "/databaseConnect/databaseConnectionPantry.php"; //DATABASE CONNECTION //DATABASE POST VARIABLES SET $app->get('/dataEntryForm', function () use($app) { $app->render('dataEntryForm.twig'); //!FORM DATA VALIDATION NEEDS ADDRESSED; IF () PARAMETERS NOT LOGICAL SOUND! try { if ($_POST['submit'] = true) { $itemName = $_POST['item_name']; $itemCount = $_POST['count']; $itemDesc = $_POST['description']; echo "Form was successfully submitted"; } else {
<?php include "vendor/autoload.php"; include "databaseConnectionFoodSearch.php"; ?> <?php Unirest\Request::verifyPeer(false); // These code snippets use an open-source library. http://unirest.io/php $response = Unirest\Request::get("https://nutritionix-api.p.mashape.com/v1_1/item?upc=<required>", array("X-Mashape-Key" => "XU83D7WqBomshL1uFNq7KVvGMz8Wp1IGNqzjsnUgU0fQWqPRk1", "Accept" => "application/json")); ?> <html> <!-- BEGIN HTML --> <body> <div class="row panel center"> <!-- FORM | Food API by UPC search --> <h4>API Food Product Search</h4> <div id="form"> <form action="food_api_upc.php" method="post"> <fieldset> <!-- ADDED RESET BUTTON --> <input type="reset" name="Reset" value="RESET" tabindex="6"> </fieldset> <fieldset> <label for="item_name">Search Food by UPC Code:</label> <input type="search" name="item_name" id="item_name" value="" tabindex="1" required /> <input type="submit" name="submit" value="SUBMIT" tabindex="5" /> <br />
public function testGetArray() { $response = Unirest\Request::get('http://mockbin.com/request', array(), array('name[0]' => 'Mark', 'name[1]' => 'John')); $this->assertEquals(200, $response->code); $this->assertEquals('GET', $response->body->method); $this->assertEquals('Mark', $response->body->queryString->name[0]); $this->assertEquals('John', $response->body->queryString->name[1]); }
/** * Get the Next Collection Date when available * * @return mixed */ public function NextCollectionDate() { $this->clearStoredResponse(); $response = Unirest\Request::get($this->api_url_nextcollectiondate, ["Content-Type" => "application/json", "Accept" => "application/json"]); $this->setStoredResponse($response); if (isset($response->code) && $response->code === 200 && isset($response->body->status) && $response->body->status === 'ok') { return $response->body->details->next_collection_date; } return false; }
<?php //First install unirest // require_once "/path/to/unirest-php/lib/Unirest.php"; require_once "vendor/mashape/unirest-php/src/Unirest.php"; $response = Unirest\Request::get("https://jsonwhois.com/api/v1/whois", array("Accept" => "application/json", "Authorization" => "Token token=f9efccf4cc7b5f311858e53379c319a2"), array("domain" => "erest.sa")); $data = $response->body; // Parsed body $obj_vars = get_object_vars($data); if ($obj_vars['status'] == "status") { echo "here"; } else { echo "not here"; } echo "<hr>"; echo "<pre>"; var_export($obj_vars); echo "</pre>";
public static function toptrack($artist_id) { $headers = array("Accept" => "application/json"); $url = "https://api.spotify.com/v1/artists/{$artist_id}/top-tracks?country=US"; $artist_top_track = Unirest\Request::get($url, $headers)->body; Flight::json($artist_top_track); }