I have a PHP page containing the following code to get latitude and longitude from a user input postal code.
But when I tried to echo the latitude and longitude, nothing is shown.
<?php
function getLnt($zip){
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result['results'][0]['geometry']['location'];
}
getLnt("750341");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$val = getLnt('90001');
echo "Latitude: ".$val['lat']."<br>";
echo "Longitude: ".$val['lng']."<br>";
?>
</body>
</html>
Please add key parameter in api request. Key value you need to replace with google API key.
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($postal_code)."&sensor=false&key=googleapi";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
if(!empty($result['results'])){
$zipLat = $result['results'][0]['geometry']['location']['lat'];
$ziplng = $result['results'][0]['geometry']['location']['lng'];
}
I've tested your code and it works perfectly, my guess is that you've exceeded your daily quota for the Google Places API Web Service.
A quick solution is to apply for a key at:
https://console.developers.google.com/
I think your problem is on API call must be on HTTP So change http to https
<?php
function getLnt($zip){
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result['results'][0]['geometry']['location'];
}
getLnt("750341");
?>
Not sure when but in 2019, we can use components in instead of address to get more accurary result.
eg: country is US and postal code is 41000
$url = "https://maps.googleapis.com/maps/api/geocode/json?components=" . urlencode('country:US|postal_code:41000') . "&key=YOUR_API_KEY";
function getLnt($zip){
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false&key=YOUR_KEY";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result['results'][0]['geometry']['location'];
}
print_r(getLnt("462021"));
Related
I'm trying to return a value from my API using PHP, api can be found here:
code is as follows:
Im not seeing the echo on my page, don't see any errors and I believing im reading the json in correctly. Any help appreciated!
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue["Age"];
?>
From what I can tell, the json is not valid on the server side (due to the "connected to db" text in front of the {} part). I think it would be a good idea to fix the server side response json data, if possible!
For now, here is a way to get the value it looks like you are intending to retrieve:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$adjusted_response = str_replace('connected to db', '', $response);
$returnvalue = json_decode($adjusted_response, true);
echo $returnvalue['tv_shows']['Age'];
?>
Output:
$ php example.php
16+
If the server side json data is fixed, I think you could shorten the code to something like this:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue['tv_shows']['Age'];
?>
The thing is that $response is returned as string , in order to fix that you need to edit your backend and make it give the response without "connected to db"
I am trying to run this API(https://developer.vimeo.com/api/reference/videos#get_video). My goal is to call the API and print out the result, because after I run the the code, nothing is printed from the API call. Appreciate if anyone can help me. Thanks :
FYI, these are my code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
require ("vendor/autoload.php");
use Vimeo\Vimeo;
$client = new Vimeo("{client_id}", "{client_secret}", "{access_token}");
$video_id ="447518879";
$response = $client->request("/videos/$video_id");
//var_dump($response['body']);
if($response['status'] === 200){
echo json_encode($response['body']['message']);
}
else {
echo json_encode($response['body']['error']);
}
?>
</body>
</html>
according to Vimeo API for PHP. the response it's an array with have body, header and status. Vimeo API PHP
to access the body. put this in your code:
var_dump($response['body']);
if you wanna print as a JSON in your page:
echo json_encode($response['body']);
I tested this script bellow in here. and it's working fine:
require 'vendor/autoload.php';
$client = new Vimeo("{client_id}", "{client_secret}", "{access_token}");
$video_id = "451686900";
$response = $client->request("/videos/$video_id");
print_r($response);
I created a program in php using CURL, in which i can take data of any site and can display it in the browser. Another part of the program is that the data can be saved in the file using file handling and after saving this data, I can find all the http links within the body tag of the saved file. My code is showing all the sites in the browser which I took, but I can not find all http links
Kindly help me out this problem.
PHP Code:
<!DOCTYPE html>
<html>
<head>
<title>Display links using Curl</title>
</head>
<body>
<?php
$GetData = curl_init();
$url = "http://www.ucertify.com/";
curl_setopt($GetData, CURLOPT_URL, $url);
curl_setopt($GetData, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($GetData);
curl_close($GetData);
$file=fopen("content.txt","w");
fputs($file,$data);
fclose($file);
echo $data;
function links() {
$file_content = file_get_contents("http://www.ucertify.com/");
$dom_obj = new DOMDocument();
#$dom_obj->loadHTML($file_content);
$xpath = new DOMXPath($dom_obj);
$links_href = $xpath->evaluate("/html/body//a");
for ($i = 0; $i<$links_href->length; $i++) {
$href = $links_href->item($i);
$url = $href->getAttribute("href");
if(strstr($url,"#")||strstr($url,"javascript:void(0)")||$url=="javascript:;"||$url=="javascript:"){}
else {
echo "<div>".$url."<div/>";
}
}
}
echo links();
?>
</body>
</html>
You can use regex like this
preg_match("/<body[^>]*>(.*?)<\/body>/is", $file_data, $body_content);
preg_match_all("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$body_content[1],$matches);
foreach($matches[0] as $d) {
echo $d."<br>";
}
If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.
This is my code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
$obj = json_decode($json_str);
echo "id: $obj->id<br>";
?>
</body>
</html>
All I want is receive the MLB752465575 part into my browser.
How can I do it?
$json_str = "https://api.mercadolibre.com/items/MLB752465575";
The above does not retrieve the data it's saving the url to the var and that's not what you want.
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.
Use curl to get the result, and json_decode to turn it into an array.
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
echo "error " . $httpcode;
curl_close($ch);
return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);
$jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);
echo "id: {$obj->id}<br>";
What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.
I want to write Web services(REST) and Consuming using Curl in php.
$books = array(
"java"=>"222",
"php"=>"333",
"c"=>"111",
"AngularJS"=>"111"
);
If you want to build your API in PHP check Slim Framework
It is a good framework and has a great documentation. I suggest you to use existing solutions because building your API from scratch needs a lot of time and expertise
Also Swagger is a good tool to define/design your rest endpoints.
To create the API - do the following:
<?php
$books = array(
"java"=>"222",
"php"=>"333",
"c"=>"111",
"AngularJS"=>"111"
);
return json_encode($books);
To use the returned value - you would do the opposite:
$books = json_decode($books_json);
First define URL END point for API and client url.
ex:API: http://www.customapi.com/java
Client URI: http://www.clientcustomapi.com/
API Snippet:
index.php
header("Content-Type: application/json;charset=utf-8");
include('functions.php');
//process client request
if(!empty($_GET['name'])){
$name = $_GET['name'];
$price = get_price($name);
if(empty($price)){
//book not found
deliveryResponse(200,"Book not found",NULL);
}else{
//response book price
deliveryResponse(200,"Book found",$price);
}
}else{
//invalid request
deliveryResponse(400,"invalid Request",NULL);
}
function.php
function get_price($find){
$books = array(
"java"=>"222",
"php"=>"333",
"c"=>"111"
);
foreach ($books as $book => $price) {
# code...
if($book==$find){
return $price;
break;
}
}
}
function deliveryResponse($status,$status_message,$data){
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response = json_encode($response);
echo $json_response;
}
Client Snippet:
<!DOCTYPE html>
<html>
<head>
<title>Book Price</title>
</head>
<body>
<form method="post" action="" name="bookprice">
<label>Book Name:</label><input type="text" name="book" id="book">
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
//simple Request
$name = $_POST['book'];
//resource address
$url ="http://www.customapi.com/$name";
//send request to resource
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER, 1);
//get response from resource
$response = curl_exec($client);
$result = json_decode($response);
if($result->data !=null){
echo $result->data;
}else{
echo"No record found";
}
}
?>