I'm trying to figure out how to encode the following:
$data[] = '';
//check if real player
if($steam_name != null){
$data['valid'] = true;
$data['url'] = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=key&vanityurl=$steam_name";
echo json_encode($data, file_get_contents($data->url));
}else{
$data['valid'] = false;
echo json_encode($data);
}
I understand how to get the data, but it seems to not be sending through.
Thanks!
My attempt as per answer below. This does not work:
$data[] = '';
//check if real player
if($steam_name != null){
$data['valid'] = true;
$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
'key' => 'key',
'vanityurl' => $steam_name,
];
$data['url'] = $url . http_build_query($params);
echo json_encode($data);
}else{
$data['valid'] = false;
echo json_encode($data);
}
You should be using http_build_query() to accomplish that.
$url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?';
$params = [
'key' => 'abc123',
'vanityurl' => $steam_name,
];
$data['url'] = $url . http_build_query($params);
That will handle the proper encoding for the parameters.
Additionally, $data is an array here, you can't call it like an object in your file_get_contents call. I'm surprised you aren't getting an exception. Also, json_encode doesn't accept parameters like that. Try this:
// Store the API response in your data array
$data['response'] = file_get_contents($data['url']);
// Return it so you can use it
return json_encode($data);
If the response is JSON, you can decode it:
$data['response'] = json_decode(file_get_contents($data['url']));
I'm making a function that can perform queries to maps.googleapis.com. I use the library GuzzleHttp assistance.
The problem I faced is when I create a function and try to access the functionality by adding parameters in URL. Looks like this function doesn't known parameters (unallocated) consequently the function that I made did not work properly.
My Controller
public function actionGetalldata() {
$url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=alskdsbeKASDJldkd&types=geocode&language=id&input=paci";
$client = new GuzzleHttp\Client();
$res = $client->request('GET', $url);
$data = $res->getBody();
$array = json_decode($data, true);
foreach ($array['predictions'] as $key) {
$detail = $this->getLatLong($key['place_id']);
}
}
You see... When I try to loop my whole data, I call getLatLong function but always fail because the function can not accept the parameters that I provide.
Below is the function
function getLatLong($placeid) {
$url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=".$placeid."&key=alskdsbeKASDJldkd";
$client = new GuzzleHttp\Client();
$res = $client->request('GET', $url);
$data = $res->getBody();
$array = json_decode($data, true);
$resultx = $array['result'];
$id = $resultx['id'];
$placeid = $resultx['place_id'];
$alamat = $resultx['adr_address'];
$lat = $resultx['geometry']['location']['lat'];
$long = $resultx['geometry']['location']['lng'];
$allData = [
'id' => $id,
'place_id' => $placeid,
'address' => $alamat,
'lat' => $lat,
'long' => $long
];
return $allData;
}
It looks like the $placeid variable is the cause.
If I directly place a static placeid value, this function working.
How can I fix it? Please help
Thank you
as title, i want to read to parse xml on url by using curl in magento 2. but it not worked.
here is my code.
$om = \Magento\Framework\App\ObjectManager::getInstance();
$curl = $om->get('Magento\Framework\HTTP\Adapter\Curl');
$curl->setConfig([
'timeout' => 5
];
$curl->write(\Zend_Http_Client::GET,$link);
$data = $curl->read();
if ($data === false) {
return false;
}
$data = preg_split('/^\r?$/m', $data, 2);
$data = trim($data[1]);
$curl->close();
Im getting json files from a site and i want it to find which ever one gets the file and use that one. Im using the $_GET Method too. There are 2 ways of getting the same file but they both require an id or a custom url from steam.
My url example: www.mysite.com?id=123123123
2 ways of getting json file:
http://steamcommunity.com/id/ID/inventory/json/730/2
http://steamcommunity.com/CUSTOMURL/76561198051643107/inventory/json/730/2
How im decoding it:
$id = $_GET['id'];
$url = "http://steamcommunity.com/id/".$id."/inventory/json/730/2";
$content = file_get_contents($url);
$playerinfo = json_decode($content, true);
$InventoryStatus = $playerinfo['success'];
some ref
$id = $_GET['id'];
$handlers =array(
'getByJson','getByDB','getBySomething'
);
$result = array('handler'=>'','data'=>'');
then call $handlers
foreach($handlers as $m){
$methodResult = call_user_func($m,$id);
if($methodResult !==false){
$result = array('handler'=>$m, 'data' => $methodResult) ;
break;
}
}
handler something like this
function getByJson($id){
$url = "http://steamcommunity.com/id/".$id."/inventory/json/730/2";
$string = file_get_contents($url);
$isJson =is_string($string) && is_object(json_decode($string)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
if($isJson){
$playerinfo = json_decode($content, true);
return $playerinfo['success'];
}
return false;
}
function getByDB($id){
// get $result
if(condition){
return $result
}
return false;
}
function getBySomething($id){
// get $result
if(condition){
return $result
}
return false;
}
I have created this test script to get data from the twitter usertimeline which I'm sure was previously working however now it returns nothing. Is there something I am missing here? (To test simply amend the constants at the top)
define('CONSUMER_KEY', '');
define('CONSUMER_SECRET', '');
define('OAUTH_TOKEN','');
define('OAUTH_SECRET','');
define('USER_ID','');
function generateSignature($oauth,$fullurl,$http_method){
// Take params from url
$main_url = explode('?',$fullurl);
$urls = explode('&',$main_url[1]);
foreach ($urls as $param){
$bits = explode('=',$param);
if (strlen($bits[0])){
$oauth[$bits[0]] = rawurlencode($bits[1]);
}
}
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.urlencode($main_url[0]).'&'.urlencode(urldecode($string));
$sign_str = CONSUMER_SECRET.'&'.OAUTH_SECRET;
return urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_str,true)));
}
function random($len,$use_chars = false,$numU = false){
$num = range(0,9);
$letu = range('A','Z');
$letl = range('a','z');
$chars = array("!","*","£","$","^","(",")","_","+");
if ($use_chars){
$arr = array_merge($num,$letu,$letl,$chars);
} else {
$arr = array_merge($num,$letu,$letl);
}
// Shuffling - new addition 11/9 to make order actually random!
shuffle($arr);
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
return implode('',$out);
}
$method = 'GET';
// Twitter still uses Oauth1 (which is a pain)
$oauth = array(
'oauth_consumer_key'=>CONSUMER_KEY,
'oauth_nonce'=>random(32),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>OAUTH_TOKEN,
'oauth_version'=>'1.0',
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=".USER_ID;
$oauth['oauth_signature'] = generateSignature($oauth,$url,$method,'');
ksort($oauth);
foreach ($oauth as $k=>$v){
$auths[] = $k.'="'.$v.'"';
}
$stream = array('http' =>
array(
'method' => $method,
// ignore_errors should be true
'ignore_errors'=>true, // http://php.net/manual/en/context.http.php - otherwise browser returns error not error content
'follow_location'=>false,
'max_redirects'=>0,
'header'=> array(
'Authorization: OAuth '.implode(', ',$auths),
'Connection: close'
)
)
);
echo $url;
$response = file_get_contents($url, false, stream_context_create($stream));
print'<pre>';print_r($stream);print'</pre>';
print'<pre>[';print_r($reponse);print']</pre>';
I found this:
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
I am not completly sure, but i think there shouldn't be a } after if ($numU){ $arr = $num;
I think it should be a open bracket. {
I found one more thing:
print'<pre>[';print_r($reponse);print']</pre>';
Here at the bottom of the code, you wrote "$reponse" instead of "$response"
I hope it helped! If it did, give it a upvote and choose as best answer!