stupid question I think.
I have an API that i want to access. if I simply put the url in my browser it returns all the results correctly.
https://api.mydomain.com/v1/name?user=user1&pass=1234
in my browser this returns array information:
{"firstname":"John","Surname":"Smith"}
I want to be able to use PHP to simply assign the results of the URL page to a variable:
$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result=parse($url);
print_r($result);
This obviously doesnt work but just looking for the correct syntax. done some research but not getting any luck. should be so simple but is not.
advice appreciated as always.
Thanks
Just make a request to your API service:
$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result = file_get_contents($url);
Then, if I understand correctly, your API returns JSON response, so you have to decode it:
$vars = json_decode($result, true);
Which will return an array with all the variables:
echo $vars['firstname']; //"John";
echo $vars['Surname']; //"Smith";
solution: file_get_contents (or maybe you'll need curl if ini_get("allow_url_fopen") !=1 ....)
$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result=parse(file_get_contents($url));
print_r($result);
hope your "parse()" function knows how to parse the result from your api call. i guess you don't know what you're doing, and next you'll be asking why the parse function is not defined :p (it looks like you're looking for json_decode , just a guess.)
i think your parse function would look like:
function parse($apiresponse){return json_decode($apiresponse,true);}
If you have the CURL library installed, you could do this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.mydomain.com/v1/name?user=user1&pass=1234');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$vars = json_decode($result, true);
//do something useful with the $vars variable
Cannot you do some search?
Take a look at Google with keywords "PHP get results from URL"
Related
I am building a PHP script that needs to use content loaded from an external webpage, but I don't know how to send/receive data.
The external webpage is http://packer.50x.eu/ .
Basically, I want to send a script (which is manually done in the first form) and receive the output (from the second form).
I want to learn how to do it because it can surely be an useful thing in the future, but I have no clue where to start.
Can anyone help me? Thanks.
You can use curl to receive data from external page. Look this example:
$url = "http://packer.50x.eu/";
$ch = curl_init($url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // you can use some options for this request
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); // or not to use them
// you can set many others options. read about them in manual
$data = curl_exec($ch);
curl_close($ch);
var_dump($data); // < -- here is received page data
curl_setopt manual
Hope, this will help you.
You may want to look at file_get_contents($url) as it is very simple to use, simpler than CURL (more limited though), so your code could look like:
$url = "http://packer.50x.eu/";
$url_content=file_get_contents($url);
echo $url_content;
Look at the documentation as you could use offset and other tricks.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get useful error messages in PHP?
I can't get this php json script to work. I'm trying to get the screen name from twitter, using their api.
Here's what I did.
$send_request = file_get_contents('https://api.twitter.com/1/users/lookup.json?screen_name=frankmeacey');
$request_contents = json_decode($send_request);
echo $request_contents->screen_name;
Why is this returning a blank value every time? I've tried changing things here and there and it's just not working...
Because the data structure you get back is an array of objects, not an object.
echo $request_contents[0]->screen_name;
That data looks to be an object inside an array. Try
echo $request_contents[0]->screen_name;
Best to check first it is an array and to get the first user from it:
if (is_array($request_contents)) {
$user_info = $request_contents[0];
}
if (isset($user_info)) {
echo $user_info->screen_name;
}
It's
$request_contents[0]->screen_name
since $request_contents is an array of objects, not the object itself.
Do a
var_dump($request_contents);
to see the structure of your json.
Your page should not be blank .. you should get an error like Notice: Trying to get property of non-object in since you are calling $request_contents->screen_name which is not valid.
Try telling PHP to output all error Using
error_reporting(E_ALL);
I also prefer CURL its faster
$ch = curl_init("https://api.twitter.com/1/users/lookup.json?screen_name=frankmeacey");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$request_contents = json_decode($result);
var_dump($request_contents[0]->screen_name);
Output
string 'frankmeacey' (length=11)
try to use
print_r($request_contents);
OR
var_dump($request_contents);
for checking array.
What I am trying to do is fetch the video information for each video from a YouTube channel and just print them out on a page, there are only 15 videos so it should be well within the usage limits.
I have read a few tutorials on websites and many SO questions but I still can't seem to put together what I need :/
The following is my attempt so far:
$url = 'http://gdata.youtube.com/feeds/api/videos?max-results=20&alt=jsonc&orderby=published&format=5&safeSearch=none&author=OpticalExpressUK&v=2';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body = curl_exec($ch);
curl_close($ch);
$data = json_decode($body, true);
echo '<pre>';
var_dump($data);
echo '</pre>';
// trying to get something out of the array!
echo $data[1]['title'];
The foundations of this came from: php youtube json decode
I've also looked at Looping code using PHP
My ideal output would be something along the lines of:
Video Title
Video Description
Rating
Anything else useful that is returned in the json response.
Embedded video
I know it may only be possible to get the direct link for the video but after reading about this I'm sure I would be able to get it embedded if I could get it that far.
I've also changed the json in the url to 'jsonc', there seems to be a big difference between what each returns, reason I changed was because I'm sure on YouTube it says to use jsonc?
Any help is much appreciated!
According to your paste on http://pastebin.com/eZ6U3RmS the right code would be:
foreach($data['data']['items'] as $item) {
echo $item['title'];
echo $item['description'];
echo $item['rating'];
echo $item['player']['default'];
// whatever you need....
}
a request to : http://gdata.youtube.com/feeds/api/videos/[VIDEO_ID_HERE] will give you an xml response with all the video data Perhaps this will help you
So I'm a beginner to all of this. I'm attempting to teach myself how to properly use CURL, and dabble a bit in API calls (don't worry, this question only relates to using CURL).
Now my original code worked just fine - I structured the request using urlencode, and the vast majority of requests leaded to the responses I was looking for. About 10% of the received responses, however, that wouldn't retrieve the results I needed. Let me give an example:
$urlToFetch = "http://lsapi.seomoz.com/linkscape/url-metrics/" . urlencode($objectURL) . "?" . $this->structureURL();
$response = ConnectionUtil::makeRequest($urlToFetch);
Using the above code would generate a $urlToFetch with the following data:
http://lsapi.seomoz.com/linkscape/url-metrics/www.alinki.com%2Fdomainlinks.php%3Fpage%3D516000?AccessID=XXXXXX&Expires=1286388878&Signature=YYYYYYYYY
This passes through CURL, and gets a response from the seoMoz API - the response, however, is missing some data. I've poked around, and found that it is an issue with how the URL is structured. For example, by changed the value from www.alinki.com%2Fdomainlinks.php%3Fpage%3D516000 to www.alinki.com/domainlinks.php?page=516000 I can retrieve all the fields I am looking for. Going by that logic, I should be able to structure a URL similar to this:
(I'm removing the http since I cannot post more than one link) lsapi.seomoz.com/linkscape/url-metrics/www.alinki.com/domainlinks.php?page=516000?AccessID=XXXXXX&Expires=1286388878&Signature=YYYYYYYYY
and retrieve all the fields I need. The problem is, when I attempt to pass that URL through to CURL, it will not complete the request. Below is the code used for the CURL request:
public static function makeRequest($urlToFetch)
{
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, "$urlToFetch");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, ConnectionUtil::CURL_CONNECTION_TIMEOUT);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$buffer = curl_exec($curl_handle);
//var_dump($buffer);
curl_close($curl_handle);
$arr = json_decode($buffer);
return $arr;
}
And I request as follows:
$urlToFetch = "http://lsapi.seomoz.com/linkscape/url-metrics/" . urlencode($objectURL) . "?" . $this->structureURL();
$response = ConnectionUtil::makeRequest($urlToFetch);
Any ideas on what silly mistake I am making?
Try using http_build_query instead of urlencode for generating your query string. It looks like the seomoz code is not handling the urlencoded data properly.
I'm sending some data to an external URL using Curl. The server sends me back a response in a string like this:
trnApproved=0&trnId=10000002&messageId=7&messageText=DECLINE
I can assign this string to a variable like this:
$txResult = curl_exec( $ch );
echo "Result:<BR>"; echo $txResult;
But how do I use the data that is sent back? I need a way to get the value of each variable sent back so that I can use it in my PHP script.
Any help would be much appreciated.
Thanks.
The default behavior of Curl is to just dump the data you get back out to the browser. In order to instead capture it to a variable, you need:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$txResult = curl_exec($ch);
That default behavior has always annoyed me. Returning the data from the curl_exec() call seems by far the more correct choice to me.
Use parse_str():
parse_str($txResult, $txArr);
var_dump($txArr);