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))?
Related
I'm tyring to use curl to print a return from a url. The code I have so far looks like this:
<?php
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
$query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$url_final = $url.''.$url_query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
the only obvious problem I know of it that the server being queried uses GET instead of POST. Are there GET alternatives to this method?
curl_setopt($ch, CURLOPT_POST, 0);
Curl uses GET by default. You were setting it to POST. You can override it if you ever need to with curl_setopt($ch, CURLOPT_HTTPGET, 1);
Use file_get_contents() function
file_get_contents
Or curl_setopt($ch, CURLOPT_HTTPGET, 1);
use
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
All these years and nobody's given the right answer; the way to build a query string is to use http_build_query() with an array. This automatically escapes everything and returns a simple string.
$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
"eligibilityType" => "Property",
"requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";
You are missing a question mark in the URL.
Should be like:
$query = '?eligibilityType=Property&...';
Also, that XML in your URL needs encoding, e.g. use the urlencode() function in PHP.
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 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 have script that calls at script via cURL. It looks like this,
Route::get('login-redirect', function() {
if (Input::has('error')) {
return Input::get('error_description');
}
if (Input::has('code')) {
$fields = array(
'grant_type' => 'password',
'username' => 'admin#local.com',
'password' => 'passwohrd',
'client_id' => 'testclient'
);
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/get-token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
$json = json_decode($result);
curl_close($ch);
$fields = array('access_token' => '3c1e6b099f172fc01304403939edf8e56904ab61');
$fieldstring = http_build_query($fields, "\n");
$url = "http://apitest.local/api/v1/me";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldstring);
$result = curl_exec($ch);
curl_close($ch);
dd($result);
}
The json returned looks like this, if I do dd($json)
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
I feel like after running it through json_decode I should be able to just output $json->error but no.
The JSON gets made in the following class, but I cannot see anything odd here either, I am doing incorrect, or do I misunderstand json_decode?
<?php
namespace Shaunpersad\ApiFoundation\Http;
use App;
use Response;
class ErrorResponse
{
public static function make($message = '', $status = 200, array $headers = array(), $options = 0)
{
$response = App::make(
'api_response_array',
array(
'content' => null,
'error' => true,
'error_description' => $message
)
);
return Response::json($response, $status, $headers, $options);
}
}
First of all, you do not have CURLOPT_RETURNTRANSFER - your curl_exec returns output buffer directly to the screen.
Second of all, it looks like you have var_dump somewhere and I cannot see where :)
Third of all - you didn't asked any direct question.
Edit
Okay i've read it few time and answer below. The dd() function is truly a var_dump wrapper but it is dumping var_dump data into json format afaics.
What you've got as an output is not from dd($json):
// this part has been output by curl_exec():
{"content":null,"error":true,"error_description":"Invalid username and password combination"}
// only this part comes from dd($json):
int(1)
Here's why:
// no CURLOPT_RETURNTRANSFER, so curl_exec() outputs result and returns true:
$result = curl_exec($ch);
// thus $result = true;
// so here $json = 1, since this is what json_decode(true) will return
$json = json_decode($result);
// then you did dd($json), so it just appended var_dump(1) to the output:
{"content":null,"error":true,"error_description":"Invalid username and password combination"}int(1)
Update
As stated in the other answers, you're not actually receiving the output because you haven't set CURLOPT_RETURNTRANSFER. So curl_exec() will echo out the response to the DOM and return true (1) as your curl request ran successfully.
You'll be able to run the below stuff by setting this in your curl request somewhere:
curl_setop(CURLOPT_RETURNTRANSFER, true);
dd() is a laravel function and this is what the documentation says:
Dump the given variable and end execution of the script.
I'd presume it is just a wrapper function for a prettier looking var_dump() (As I don't use laravel, I wouldn't know its exact output.).
What you want is to decode the $result that is returned from your cUrl. Something like this should suffice:
$data = json_decode($result);
echo $data->error_description;
The successfully decoded object looks like this:
stdClass Object
(
[content] =>
[error] => 1
[error_description] => Invalid username and password combination
)
Example
You can even test your boolean error value like this now:
if($data->error) {
//....true
} else {
//....false
}
Ruby Code:
# Turn hash input into JSON, store it in variable called "my_input"
my_input = { "itemFilter" => { "keywords" => "milk" }}.to_json
# Open connection to website.com
#http = Net::HTTP.new("website.com")
# Post the request to our API, with the "findItems" name and our JSON from above as the value
response_code, data = #http.post("/requests", "findItems=#{my_input}",
{'X-CUSTOM-HEADER' => 'MYCUSTOMCODE'})
my_hash = Crack::JSON.parse(data)
my_milk = my_hash["findItems"]["item"].first
PHP code:
$requestBody = json_encode(array("itemFilter" => array( "keywords" => "milk" )));
$headers = array ('X-CUSTOM-HEADER: MYCODE');
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, 'website.com/request/findItems=');
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
print_r($response);
Take a look at json_encode, json_decode and the cURL extension.
Found the problem.. Thanks for the input. I put a trailing slash where it was not required, and the json_encode was putting brackets around the encoding, and it didn't need them.