In my script I have a function that retrieves JSON information from the Github API, https://api.github.com/users/octocat/repos.
I want to have a different function to get all the languages used by (in this case) octocat and then count how many times he used the language.
I was thinking of this:
foreach($json['language'] as $RepoLanguage)
{
echo $RepoLanguage;
}
but that won't work, any suggestions/ideas?
I think the main reason is that you did not specify the User Agent as specified here: https://developer.github.com/v3/#user-agent-required
Did you check what result you have in the $json?
Here's a working example.
<?php
function get_content_from_github($url) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,1);
curl_setopt($ch,CURLOPT_USERAGENT,'My User Agent');
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$json = json_decode(get_content_from_github('https://api.github.com/users/octocat/repos'), true);
foreach($json as $repo) {
$language = $repo['language'];
}
?>
Related
Basically I want to have one centralized file (preferably .php or .txt).. In it I will define the version and online statuses of my 3 API's (login, register, and stats)
I will somehow link it to my system status page and call upon them in my html with like $version, $login, $register, or $stats and they will automatically display whatever is defined in the centralized file.
My stats page (https://epicmc.us/status.php).. I want to define it all from a seperate file and call upon it in the HTML.
I tried making an external file called check.php and put this in it:
<?php
$version = "1.0.0";
$login = 'online';
$register = 'online';
$stats = 'online';
echo json_encode(compact('version','login','register','stats'));
?>
and then in my stats page I called upon it with
<?php
$data= json_decode(file_get_contents('https://epicmc.us/api/bridge/check.php'),true);
echo $version;
echo $login;
echo $register;
echo $stats;
?>
The page is just blank though.
How would you go about implementing this into my stats page code?
http://pastebin.com/nREdfH1u
A good solution here would be to curl your file.
As you already return a JSON string containing your values, just curl your 'check.php' file and json_decode the response.
One of the advantages of this method is that you can access these informations from other domains.
You should be able to get all the values easily.
Example :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'check.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // to return the response in a variable and not output it
// $result contains the output string
$result = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$array_response = json_decode($result, true);
// echo $array_response['version']...
I've made a curl request. I put the curl instructions in one class function:
class Curly {
var $data;
function GetRequest($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$this->data = curl_exec($ch);
curl_close($ch);
//this is what i was missing --> return $this->data;
}
I put the database query in another class function.
include('class.curly.php');
class mongoSearchForInfoOnEsd {
public function getEsdsFbInfo($esdID) {
$mongoApiKey = "xx";
$requestParams= "xx";
$url = "xx";
$fbInfo = (new Curly)->GetRequest($url);
//this is what i was missing --> return $fbInfo;
}
In the index.php, an HTTP post from a webhook is coming through, in which parsing through some strings to obtain 2 ids is handled. I then send one of those ids to the mongodb curl request, everything goes good. The correct response comes back, I only know this b/c of the var_dump of the var_dump in the curly class....BUT in the index file I'm struggling to get to get the data out of the var and assign its values to any variable I want.
How can I get the data out? I know its there, but where?
I'm so stuck.
# get ytID from http post
#get EsdID from http post
$httpPostData = file_get_contents('php://input');
$postDataDecoded = urldecode($httpPostData);
$ytID = substr($postDataDecoded, strpos($postDataDecoded, "docid=") + strlen("docid="), );
$esdID = substr($postDataDecoded, strpos($postDataDecoded, "m\": \"") + strlen ("m\": "),;
*$esdData = (new mongoSearchForInfoOnEsd)->getEsdsFbInfo("$esdID");*
$obj = json_decode($esdData, true);
echo $obj;
OK, I've added return and I can see the data, but no operations are working on returned data.
edit ---> put return in both classes, now its fully operational.
As lazyhammer said you need to write the following in the end of your method GetRequest($url)
return $this->data;
Also, in a class, a function is called a method.
To be more explicit.
var_dump doesn't return the data. it's only sending them to the client(your browser) which will display it.
to return the data computed in your method back to the caller, you need to use the keyword return at the end of your method.
When your computer will see return he bring back the data to the caller. it means everything you write after return won't be executed.
Just because you are assigning a value to the class variable data doesn't mean that value is being returned when you call the function getRequest. Therefore, in order to use the data from an outside class, you need to return the final value:
function GetRequest($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$this->data = curl_exec($ch);
curl_close($ch);
return $this->data;
}
You may not even need to keep the variable $data around, unless there is more to your code that you are not showing, you could simply return curl_exec($ch)
To further answer your question from your comments below, this is from php.net:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
As you can see, var_dump is used for display purposes only.
I'm trying to request information about a domain without success; code:
<?php
echo file_get_contents('https://sb-ssl.google.com/safebrowsing/api/lookup?client=asasd&apikey=MYKEY&appver=1.5.2&pver=3.0&url=http%3A%2F%2Fwww.onet.pl%2F');
?>
Why isn'tit working?
//function for getting the data from url
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Then get the content using the function call :
$returned_content = get_data('your url');
get_file_contents() has huge security threat – and many servers have disabled this feature in PHP.
Why isn'tit working?
because wrong url
http://www.google.com/safebrowsing/diagnostic?site=http://example.com/
just take a look at the documentation:
with URLs, you should use urlencode()
fopen wrapper has to be enabled (same as for fopen())
maybe the url is wrong - when i copy your URL and try to open it, i get a pageload-failure.
I am currently trying to fetch some facebook data, which I then want to access in Javascript. Specifically, I am trying to access some characteristics of the user's friends.
So I am getting the user's friend list using file_get_contents to his graph API URL.
This provides me with an array of friend ids.
As I need a characteristic from each friend, I am doing:
foreach($dataarray as $friend) {
$friendurl = "https://graph.facebook.com/".$friend->id."?access_token=".$token."";
$fdata = json_decode(file_get_contents($friendurl));
if($fdata->gender == "male") {
array_push($fulldata, $fdata->name);
}
}
Having this code piece seems to break the javascript code, as none of my alert instructions are ran.
Also, inserting a break after the if, so that only one file_get_contents is done, seems to make the code runnable (but I obviously need to go through all of the friends).
How can I solve this?
I would use jQuery or xmlHttpRequest to do the HTTP GET, but somehow I always seem to get back a status code of 0, with an empty response.
Edit:
Here is the JS code:
<script type="text/javascript">
function initialize() {
alert('Test1');
<?php
$fulldata = array();
$data = $result->data;
foreach($data as $friend) {
$friendurl = "https://graph.facebook.com/".$friend->id."?access_token=".$token."";
//echo("alert(\"".$friendurl."\");");
$fdata = json_decode(file_get_contents($friendurl));
if($fdata->hometown->name) {
array_push($fulldata, $fdata->hometown->name);
}
}
echo ("alert(\"".count($fulldata)."\")");
?>
}
</script>
I should've also added that this is being done on a page embedded into facebook using the canvas feature.
Try...
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($ch);
curl_close ($ch);
}
foreach($dataarray as $friend){
$friendurl = "https://graph.facebook.com/".$friend->id."?access_token=".$token."";
$fdata = json_decode(curl($friendurl));
if($fdata->gender == "male"){
array_push($fulldata, $fdata->name);
}
}
Maybe FGC is disabled but you don't get any notifications/warnings.
Code from comment:
error_reporting(E_ALL); ini_set("display_errors", 1);
Note that you are doing cross-domain AJAX call which is prohibited for security reasons.
You can do the api call on the server and echo the data to the client side JS, or you can build a php proxy return the result of the Graph API call(As the proxy is at your own server, they are in the same domain).
I'm starting to help a friend who runs a website with small bits of coding work, and all the code required will be PHP. I am a C# developer, so this will be a new direction.
My first stand-alone task is as follows:
The website is informed of a new species of fish. The scientific name is entered into, say, two input controls, one for the genus (X) and another for the species (Y). These names will need to be sent to a website in the format:
http://www.fishbase.org/Summary/speciesSummary.php?genusname=X&speciesname=Y&lang=English
Once on the resulting page, there are further links for common names and synonyms.
What I would like to be able to do is to find these links, and call the URL (as this will contain all the necessary parameters to get the particular data) and store some of it.
I want to save data from both calls and, once completed, convert it all into xml which can then be uploaded to the website's database.
All I'd like to know is (a) can this be done, and (b) how difficult is it?
Thanks in advance
Martin
If I understand you correctly you want your script to download a page and process the downloaded data. If so, the answers are:
a) yes
b) not difficult
:)
Oke... here some more information: I would use the CURL extension, see:
http://php.net/manual/en/book.curl.php
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
?>
I used a thing called snoopy (http://sourceforge.net/projects/snoopy/) 4 years a go.
I took about 500 customers profiles from a website that published them in a few hours.
a) Yes
b) Not difficult when have experience.
Google for CURL first, or allow_url_fopen.
file_get_contents() will do the job:
$data = file_get_contents('http://www.fishbase.org/Summary/speciesSummary.php?genusname=X&speciesname=Y&lang=English');
// Отправить URL-адрес
function send_url($url, $type = false, $debug = false) { // $type = 'json' or 'xml'
$result = '';
if (function_exists('curl_init')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
} else {
if (($content = #file_get_contents($url)) !== false) $result = $content;
}
if ($type == 'json') {
$result = json_decode($result, true);
} elseif ($type == 'xml') {
if (($xml = #simplexml_load_file($result)) !== false) $result = $xml;
}
if ($debug) echo '<pre>' . print_r($result, true) . '</pre>';
return $result;
}
$data = send_url('http://ip-api.com/json/212.76.17.140', 'json', true);