I am working on apps where i try to use curl.Before that i try to use file_get_contents() but that was not working on my server due to allow_url issue ( i tried to contact hosting but not resolve yet so i try alternate ).So i used curl to get data from remote site.I get data using this code :
$url="http://api.hostip.info/get_html.php?ip=182.188.193.238";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
print_r($result);
when i print i get Country: PAKISTAN (PK) City: Lahore IP: 182.188.193.238.I want to get the country from this string.I tried like this but get empty result like $data = json_decode($result,true); . Json decode returns empty result.I think only way is to break that string ? Thanks for any hints in advance.I want to get the country name from the result.
As per API doc, You can get also json response using get_json.php
Just used get_json.php instead of get_html.php.
Your code should be :
$url="http://api.hostip.info/get_json.php?ip=182.188.193.238";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$data = json_decode($result,true);
print_r($data);
Use preg_match
preg_match('/Country: (?P<country>\w+)/', $result, $matches);
print_r($matches);
Output:
Array
(
[0] => Country: PAKISTAN
[country] => PAKISTAN
[1] => PAKISTAN
)
So you would get country name with
$countryName = $matches['country'];
As #hardik solanki said, there is also JSON endpoint get_json.php.
$url = "http://api.hostip.info/get_json.php?ip=182.188.193.238";
To get country from JSON response, use this:
$response = json_decode($result);
$countryName = $response->country_name;
If you don't mind, use get_content
$content = get_content("http://api.hostip.info/get_html.php?ip=182.188.193.238");
$country = stristr($content, 'Country: ');
$country = stristr($country, 'City:', true);
$country= ucfirst(str_replace('Country: ', '', $country));
echo $country;
Related
Just wondering if anyone knew what I was doing wrong here?
I am trying to get data from an API for bitcoin via php. However, I am getting no results from my php page.
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "ID: ". $json_data["id"];
However I am getting nothing show at all on the php page. If I use the code below, It works and dumps out the entire information. But, I would prefer to obtain the information separately, instead of one big dump.
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
var_dump(json_decode($result, true));
Anyone have any ideas why the first code block isn't working? Thanks! Very new to API and Json
Using cURL is much better
Updated code (needs error checking)
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json_data = json_decode($result, true);
foreach ($json_data as $item)
echo "ID: ". $item["id"];
I have printed the result it will produce following output
echo "<pre>";
print_r(json_decode($result, true));
Array
(
[0] => Array
(
[id] => bitcoin
[name] => Bitcoin
[symbol] => BTC
[rank] => 1
[price_usd] => 3821.37
[price_btc] => 1.0
[24h_volume_usd] => 2089880000.0
[market_cap_usd] => 63298556016.0
[available_supply] => 16564362.0
[total_supply] => 16564362.0
[percent_change_1h] => -1.72
[percent_change_24h] => -4.57
[percent_change_7d] => -15.76
[last_updated] => 1505359771
[price_eur] => 3214.536444
[24h_volume_eur] => 1758007056.0
[market_cap_eur] => 53246745321.0
)
)
so you can use foreach loop if your api contain multiple
$data=json_decode($result, true);
foreach($data as $key=>$val){
echo $val->id;
}
full code
<?php
$url = "https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=EUR";
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$data=json_decode($result, true));
foreach($data as $key=>$val){
echo $val->id;
}
The setting you are looking for is allow_url_fopen.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen(), and the other is to use cURL.
I recommend using cURL over file_get_contents() anyways, since it was built for this.
I wanted to try to get data from a JSON string which is loaded from another page. I currently have used Curl to get the data from the webpage but I can't acces the data in it.
I've already tried:
var_dump(json_decode($result->version, true));
var_dump(json_decode($result[3][0]["date"], true));
But this does't seem to work as it always returns NULL
$url="https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
First decode the JSON, then get the properties you want. Like this:
$yourObject = json_decode($result);
var_dump($youObject->version);
this is working for me.
<?php
$url = "https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201";
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
$data = json_decode($result);
//echo $data->data[0]['date'];
echo "<pre>";
print_r($data->data[0]->date);
}
?>
if you want to get date of all index then try this in loop.
Firstly if your using GET there is no need to use CURL,
$result = file_get_contents(https://roosters.deltion.nl/api/roster?group=AO2B&start=20160125&end=20160201);
Will work just as well without any of the overhead. I suspect that your CURL isn't returning the page content so using file_get_contents() will fix it.
If I make this call with file_get_contents, it is returning the data, but with curl it show error true, code: 204, with all empty arrays, I m making post of single query string, I am just a novice in programming any help, thanks.
Array ( [error] => 1 [dname_avail] => [domname] => Array ( [tld_code] => )
<?php
$json = '';
if(isset($_POST['querystring'])){
$string_sanitised = $_POST['querystring'];
$query_var= str_replace(" ","",$string_sanitised);
// set HTTP header
$headers = array('Content-Type: application/json',);
// *** create the call to the API and pass parameters along
//apikey =xx67676876868686868686
$url = 'http://api.mydomain.com/domlook/domname/'.$query_var.'/apikey/xx67676876868686868686/';
// Open connection
$ch = curl_init();
// Set the url, number of GET vars, GET data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute request
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// get the result and parse to JSON
$result_arr = json_decode($result, true);
print_r($result_arr);
}else{
echo "error";
}
?>
This example only displayed a blank page for me.
This one did as well.
I've got the latest version of PHP and cURL set up properly, as far as I know so there shouldn't be any problem at that end. I'd prefer JavaScript to retrieve products but I'm open minded.
I happen to not be highly skilled, but I'd like to get my foot in the door.
edit: I will show you the code that doesn't work, and the error it is giving me.
<?php
// Your developer key
$cj_id = "My ID - omitted for privacy.";
// Your website ID
$website_id = "Also removed for privacy.";
// Keywords to search for
$keywords = "credit+card";
// URL to query with cURL
$url = "https://product-search.api.cj.com/v2/product-search?website-id=$website_id&keywords=$keywords";
// Initiate the cURL fetch
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send authorization header with the CJ ID. Without this, the query won't work
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$cj_id));
$result = curl_exec($ch);
// Put the results to an object
$resultXML = simplexml_load_string($result);
// Print the results
print "<pre>";
print_r($resultXML);
print "</pre>";
?>
Now, this is the error that it's giving me.
SimpleXMLElement Object
(
[error-message] => Invalid Key provided. Valid keys are: advertiser-ids, advertiser-sku, currency, high-price, high-sale-price, isbn, keywords, low-price, low-sale-price, manufacturer-name, manufacturer-sku, page-number, records-per-page, serviceable-area, sort-by, sort-order, upc, website-id
)
You have a error in your URL, try this:
$url = "https://product-search.api.cj.com/v2/product-search?website-id=$website_id&keywords=$keywords";
instead of :
$url = "https://product-search.api.cj.com/v2/product-search?website-id=$website_id&keywords=$keywords";
<?php
echo '<pre>';
$url='https://product-search.api.cj.com/v2/product-search?website-id=your-id-key-here&advertiser-ids=4415206&records-per-page=999&serviceable-area=US';
$CJ_KEY='0085eb59c8928f028ba5b27bccfe17cdd20cf4e9079b977b2cc6df72752abab9205676a2f7ee67befe9dccab85f656ef46aba49e500faccbf75dfc6e03f655334d/00848a3f9bf0e13525bce27f008d6245c3e42ae80f2d80a8d9d2220807ca386f4b10146cbbcfff06aafb5e49c03a3318213389dee7861abb2dd7229470390a89c9';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, FAlSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$CJ_KEY));
$curl_results = curl_exec($ch);
$xml = simplexml_load_string($curl_results);
var_dump($xml);
// Loop Insert Product to database
echo '<pre>';
// if you no set: records-per-page=999, default get 50 products latest
// advertiser-ids=4415206 is Id of Advertiser in CJ, you can replace other id ,
Hope helpful for you , good luck !
?>
I am using an API that returns JSON from a GET request
Eg.
https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}
Returns
{
"call_duration": 4,
"total_amount": "0.00400"
}
How can I call this page from within a script and save call_duation and total_amount as separate variables?
Something like the following?:
$call_duration =
$_GET[https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}, 'call_duration'];
$_GET[] contains the get parameters that are passed to your code - they don't generate a GET request.
You could use curl to make your request:
$ch = curl_init("https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output);
If PHP has allow_url_fopen enabled you can simply do
json_decode(file_get_contents('https://api.domain.com/v1/Account/{auth_id}/Call/{call_uuid}'))
Otherwise you'll have to resort to using something like Curl to get the request going. $_GET is a superglobal array which doesn't actually do anything. It only contains what the script was started with. It does not make any requests itself.
Use curl to get the JSON, then json_decode to decode it into PHP variables
$auth_id = 'your auth id here';
$call_uuid = 'your call_uuid here';
// initialise curl, set URL and options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.domain.com/v1/Account/{$auth_id}/Call/{$call_uuid}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// get the response and decode it
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$call_duration = $response['call_duration'];
$total_amount = $response['total_amount'];