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.
Related
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";
}
?>
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;
I have a little problem. My code:
<?php
$url = "http://xxxx/duplicate";
$data = array (
userId => xxxx, // authentication userId
loginToken => 'xxxx', // authentication loginToken
"id" => "123456",
'section' => 'LotRental',
);
$data_string = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
echo json_encode($data_string);
?>
but it creates this post:
userId=xxxx&loginToken=xxxx&id=123456§ion=LotRental
it changes "section" to "§ion"
request shoud look like:
userId=xxxx&loginToken=xxxx&id=123456§ion=LotRental
how to fix it?
Thanks
update:
I can duplicate my item by two ways: this curl above or just type url in browser
when I execute my php script I'm getting error from a serwer:
HTTP ERROR: 405
METHOD_NOT_ALLOWED
RequestURI=xxxx/duplicate.dispatch
But when I type in browser
http://xxxx/duplicate?userId=xxxx&loginToken=xxxx&id=123456§ion=LotRental
it works fine
The script itself is OK wrt. to its output. It looks like you're viewing the output of this script in a browser. You must then properly HTML-encode the output before sending it to the browser, but instead you seem to JSON-encode it. So instead of:
echo json_encode($data_string);
you would use:
echo htmlentities($data_string);
I am sending payment info to Virtual merchant payment gateway for payment system using curl. This is my code :
$Url= "https://www.myvirtualmerchant.com/VirtualMerchant/process.do";
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Include header in result? (0 = yes, 1 = no)
// curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$fields = array(
'ssl_card_number'=>urlencode($_POST['ssl_card_number']),
'ssl_exp_date'=>urlencode($_POST['ssl_exp_date']),
'ssl_cvv2cvc2'=>urlencode($_POST['ssl_cvv2cvc2']),
'ssl_avs_address'=>urlencode($_POST['ssl_avs_address']),
'ssl_avs_zip'=>urlencode($_POST['ssl_avs_zip']),
'ssl_merchant_id'=>urlencode($_POST['ssl_merchant_id']),
'ssl_user_id'=>urlencode($_POST['ssl_user_id']),
'ssl_pin'=>urlencode($_POST['ssl_pin']),
'ssl_transaction_type'=>urlencode($_POST['ssl_transaction_type']),
'ssl_amount'=>urlencode($_POST['ssl_amount']),
'ssl_show_form'=>urlencode($_POST['ssl_show_form']),
'TransactionType'=>urlencode($_POST['TransactionType'])
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Download the given URL, and return output
echo $output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
print_r($output);
But in $output i am getting nothing, not any error or message. Am i doing it wrong ? please tell me ?
First I'd check your mechant_id, pin, etc. Below is working code I created after working through a similar problem.
<html>
<body>
<p>--start--</p>
<?php
//if you have a live account don't use the "demo" post url it won't work
$post_url = 'https://www.myvirtualmerchant.com/VirtualMerchant/process.do';
//replace the xxx's with your proper merchant_id, etc.
//they will give you these when you activate your account
//I've set form to not show, and ssl_result_format =>ascii to get a string returned
$fields = array(
'ssl_merchant_id' =>'xxxxxx',
'ssl_user_id' =>'xxx',
'ssl_pin' =>'xxxxx',
'ssl_show_form' =>'false',
'ssl_result_format' =>'ascii',
'ssl_test_mode' =>'false',
'ssl_transaction_type' =>'ccsale',
'ssl_amount' =>'1.44',
'ssl_card_number' =>'5000300020003003',
'ssl_exp_date' =>'1214',
'ssl_avs_address' =>'Test 3',
'ssl_avs_zip' =>'123456',
'ssl_cvv2cvc2' =>'123',
);
//build the post string
$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .=$key.'='.$value.'&'; }
rtrim($fields_string, "&");
//open curl session
// documentation on curl options at http://www.php.net/curl_setopt
$ch = curl_init();
//begin seting curl options
//set URL
curl_setopt($ch, CURLOPT_URL, $post_url);
//set method
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//set post data string
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//these two options are frequently necessary to avoid SSL errors with PHP
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
if($result === FALSE) {
//post failed
die(curl_error($ch));
} else {
//got a response
//some people seem to get name/value pairs delimited with "&"
//but currently mine is \n
//support told me there's no way to change it..
$response_array = explode("\n",$result);
//make it nice and useful
foreach( $response_array as $k=>$v ){
$v=explode("=",$v);
$a[$v[0]]=$v[1];
}
//show the whole array
print_r($a);
//use a specific return value
//returns "APPROVAL" if it went through
echo('<h1>'. $a[ssl_result_message] . '</h1>');
}
?>
<p>--end--</p>
</body>
</html>
The code above should net you a screen like this:
--start--
Array ( [ssl_card_number] => 50**********3003 [ssl_exp_date] => 1214 [ssl_amount] => 1.44 [ssl_customer_code] => [ssl_salestax] => [ssl_invoice_number] => [ssl_description] => [ssl_departure_date] => [ssl_completion_date] => [ssl_company] => [ssl_first_name] => [ssl_last_name] => [ssl_avs_address] => Test 3 [ssl_address2] => [ssl_city] => [ssl_state] => [ssl_avs_zip] => 123456 [ssl_country] => [ssl_phone] => [ssl_email] => [ssl_result] => 0 [ssl_result_message] => APPROVAL [ssl_txn_id] => AA49315-1234567-F78F-468F-AF1A-F5C4ADCFFB1E [ssl_approval_code] => N53032 [ssl_cvv2_response] => [ssl_avs_response] => [ssl_account_balance] => 0.00 [ssl_txn_time] => 01/15/2014 11:53:15 AM )
APPROVAL
--end--
Make sure you delete all these test purchases when you finished testing. I'm told they will inhibit your real purchases from posting.
try this to find out the error
var_dump(curl_error($ch));
before and calling curl_exec($ch);
You are calling an HTTPS page. Please refer to following link
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
Try to find error give this code before curl close:--
echo "Curl Error :--" . curl_error($ch);
if no error found do like this:-
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
then
print_r($result);
exit;
Try this:
$output = curl_exec($ch);
$response = curl_getinfo($ch);
echo "<pre>";
print_r($response);
echo "</pre>";
Hope you get the response :)
This code return null value. Value is: {}
I checked it, CURL is enabled but still it returns null -> {}. Do you get the results?
Please help me asap.
PHP code is blow:
$urlstring="http://www.google.com/loc/json";
$ch=curl_init($urlstring);
$cell_towers = array();
$row=new stdClass();
$row->location_area_code=3311;
$row->mobile_network_code=71;
$row->cell_id=32751;
$row->mobile_country_code=404;
$cell_towers[]=$row;
$param = array(
'host'=> 'localhost',
'version' => '1.1.0',
'request_address' => true,
'cell_towers' => $cell_towers
);
$param_json=json_encode($param);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$param_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$result=curl_exec($ch);
echo $result;
Try replacing the new stdClass() with a simple array().
Also did you try to echo $param_json? Is the data properly formatted?
Finally, I'm surprised the POSTFIELDS is the whole JSON data. Are you sure it shouldn't be something like curl_setopt($ch,CURLOPT_POSTFIELDS, array("data" => $param_json))?