I have a radio service Icecast, And I need to get the data of the transmission, As are the listeners, Current song, etc.
The information is given to me in a Json file: http://213.5.176.74:8002/status-json.xsl
What I need is to create variables to store the listeners data, current song, etc.
I tried to do this:
<?php
$url="http://213.5.176.74:8002/status-json.xsl";
// Initiate curl
$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);
// Will dump a beauty json :3
var_dump(json_decode($result, true));
When I write the code above I get this:
array(1) { ["icestats"]=> array(7) { ["admin"]=> string(19) "icemaster#localhost" ["host"]=> string(9) "127.0.0.1" ["location"]=> string(5) "Earth" ["server_id"]=> string(13) "Icecast 2.4.3" ["server_start"]=> string(31) "Wed, 08 Feb 2017 19:16:01 +0000" ["server_start_iso8601"]=> string(24) "2017-02-08T19:16:01+0000" ["source"]=> array(13) { ["audio_info"]=> string(10) "bitrate=24" ["genre"]=> string(3) "POP" ["listener_peak"]=> int(1) ["listeners"]=> int(0) ["listenurl"]=> string(28) "http://127.0.0.1:8002/stream" ["server_description"]=> string(6) "(null)" ["server_name"]=> string(6) "AutoDJ" ["server_type"]=> string(10) "audio/mpeg" ["server_url"]=> string(19) "https://habbosk.com" ["stream_start"]=> string(31) "Wed, 08 Feb 2017 19:19:02 +0000" ["stream_start_iso8601"]=> string(24) "2017-02-08T19:19:02+0000" ["title"]=> string(21) "AKONs Lonely Lyrics" ["dummy"]=> NULL } } }
The problem is that I do not know how to make variables with the previous content, so I use it on the website where I will put the statistics of the radio.
I appreciate your answers.
I speak Spanish, and I use google translate
Greetings.
Building on what you have... you are close!
You just need to parse the variable from the nested arrays returned to you.
Here is your same data variable, separated to show the nested array relationships:
array(1) {
["icestats"]=> array(7) {
["admin"]=> string(19) "icemaster#localhost" ["host"]=> string(9) "127.0.0.1" ["location"]=> string(5) "Earth" ["server_id"]=> string(13) "Icecast 2.4.3" ["server_start"]=> string(31) "Wed, 08 Feb 2017 19:16:01 +0000" ["server_start_iso8601"]=> string(24) "2017-02-08T19:16:01+0000"
["source"]=> array(13) {
["audio_info"]=> string(10) "bitrate=24" ["genre"]=> string(3) "POP" ["listener_peak"]=> int(1) ["listeners"]=> int(0) ["listenurl"]=> string(28) "http://127.0.0.1:8002/stream" ["server_description"]=> string(6) "(null)" ["server_name"]=> string(6) "AutoDJ" ["server_type"]=> string(10) "audio/mpeg" ["server_url"]=> string(19) "https://habbosk.com" ["stream_start"]=> string(31) "Wed, 08 Feb 2017 19:19:02 +0000" ["stream_start_iso8601"]=> string(24) "2017-02-08T19:19:02+0000" ["title"]=> string(21) "AKONs Lonely Lyrics" ["dummy"]=> NULL
}
}
}
So here is your original code...
<?php
$url="http://213.5.176.74:8002/status-json.xsl";
// Initiate curl
$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);
And here we process the variable working deeper
$result = json_decode( $result, true ); /* UPDATED */
$stats = $result['icestats'];
echo 'Admin is: ' . $stats['admin'];
echo 'Server ID is: ' . $stats['server_id'];
// and deeper
$source = $stats['source'];
echo 'Genre is: ' . $source['genre'];
echo 'Song Title is: ' . $source['title'];
Related
I am trying to get response from YTS API, however I can't understand what went wrong here. I do believe that status and status_message are objects.
Errors
PHP Notice: Trying to get property 'status' of non-object in /var/www/html/movies/inc/YTS.php on line 232
Notice: Trying to get property 'status' of non-object in /var/www/html/movies/inc/YTS.php on line 232
PHP Notice: Trying to get property 'status_message' of non-object in /var/www/html/movies/inc/YTS.php on line 233
Notice: Trying to get property 'status_message' of non-object in /var/www/html/movies/inc/YTS.php on line 233
PHP Fatal error: Uncaught Exception: API request failed. Error was: in /var/www/html/movies/inc/YTS.php:233
Code:
$url = "https://yts.mx/api/v2/list_movies.json?limit=1";
private function getFromApi($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
throw new Exception("Curl request failed: " . $e);
}
else {
$data = json_decode($response);
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
}
curl_close($curl);
}
var_dump($data)
object(stdClass)#1 (4) { ["status"]=> string(2) "ok" ["status_message"]=> string(20) "Query was successful" ["data"]=> object(stdClass)#2 (4) { ["movie_count"]=> int(40807) ["limit"]=> int(1) ["page_number"]=> int(1) ["movies"]=> array(1) { [0]=> object(stdClass)#3 (26) { ["id"]=> int(41604) ["url"]=> string(66) "https://yts.mx/movies/a-chinese-odyssey-part-one-pandoras-box-1995" ["imdb_code"]=> string(9) "tt0112778" ["title"]=> string(41) "A Chinese Odyssey Part One: Pandora's Box" ["title_english"]=> string(41) "A Chinese Odyssey Part One: Pandora's Box" ["title_long"]=> string(48) "A Chinese Odyssey Part One: Pandora's Box (1995)" ["slug"]=> string(44) "a-chinese-odyssey-part-one-pandoras-box-1995" ["year"]=> int(1995) ["rating"]=> float(7.6) ["runtime"]=> int(87) ["genres"]=> array(3) { [0]=> string(6) "Action" [1]=> string(9) "Adventure" [2]=> string(6) "Comedy" } ["summary"]=> string(391) "Fantasy adventure about the arrival of Buddhism in China. When the Goddess of Happiness tosses the Longevity Monk and his disciples out of heaven (because the Monkey King tried to attain immortality), the Monkey King is reincarnated as the Joker. He now spends his time chasing two jealous women. When one of them is dying, the Joker goes back in time in an attempt to save her. —Anonymous" ["description_full"]=> string(391) "Fantasy adventure about the arrival of Buddhism in China. When the Goddess of Happiness tosses the Longevity Monk and his disciples out of heaven (because the Monkey King tried to attain immortality), the Monkey King is reincarnated as the Joker. He now spends his time chasing two jealous women. When one of them is dying, the Joker goes back in time in an attempt to save her. —Anonymous" ["synopsis"]=> string(391) "Fantasy adventure about the arrival of Buddhism in China. When the Goddess of Happiness tosses the Longevity Monk and his disciples out of heaven (because the Monkey King tried to attain immortality), the Monkey King is reincarnated as the Joker. He now spends his time chasing two jealous women. When one of them is dying, the Joker goes back in time in an attempt to save her. —Anonymous" ["yt_trailer_code"]=> string(11) "ZPri1X1RVeo" ["language"]=> string(2) "cn" ["mpa_rating"]=> string(0) "" ["background_image"]=> string(95) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/background.jpg" ["background_image_original"]=> string(95) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/background.jpg" ["small_cover_image"]=> string(96) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/small-cover.jpg" ["medium_cover_image"]=> string(97) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/medium-cover.jpg" ["large_cover_image"]=> string(96) "https://yts.mx/assets/images/movies/a_chinese_odyssey_part_one_pandoras_box_1995/large-cover.jpg" ["state"]=> string(2) "ok" ["torrents"]=> array(2) { [0]=> object(stdClass)#4 (10) { ["url"]=> string(72) "https://yts.mx/torrent/download/0575F561D71DD1961F01FC2CBBE22AF5598A6CF1" ["hash"]=> string(40) "0575F561D71DD1961F01FC2CBBE22AF5598A6CF1" ["quality"]=> string(4) "720p" ["type"]=> string(6) "bluray" ["seeds"]=> int(0) ["peers"]=> int(0) ["size"]=> string(9) "810.78 MB" ["size_bytes"]=> int(850164449) ["date_uploaded"]=> string(19) "2022-04-20 20:07:01" ["date_uploaded_unix"]=> int(1650478021) } [1]=> object(stdClass)#5 (10) { ["url"]=> string(72) "https://yts.mx/torrent/download/633A2CAE8DE3C9F50B2E3B89A5BC6304E4770BFE" ["hash"]=> string(40) "633A2CAE8DE3C9F50B2E3B89A5BC6304E4770BFE" ["quality"]=> string(5) "1080p" ["type"]=> string(6) "bluray" ["seeds"]=> int(0) ["peers"]=> int(0) ["size"]=> string(7) "1.63 GB" ["size_bytes"]=> int(1750199173) ["date_uploaded"]=> string(19) "2022-04-20 21:16:40" ["date_uploaded_unix"]=> int(1650482200) } } ["date_uploaded"]=> string(19) "2022-04-20 20:07:01" ["date_uploaded_unix"]=> int(1650478021) } } } ["#meta"]=> object(stdClass)#6 (4) { ["server_time"]=> int(1650488761) ["server_timezone"]=> string(3) "CET" ["api_version"]=> int(2) ["execution_time"]=> string(4) "0 ms" } } Query was successful
Code that was working using file_get_content(), but knew to fail sometimes and so I was told to use curl.
private function getFromApi($url)
{
if (!$data = file_get_contents($url)) {
$error = error_get_last();
throw new Exception("HTTP request failed. Error was: " . $error['message']);
} else {
$data = json_decode($data);
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
}
}
Current code
<?php
$url = "https://yts.mx/api/v2/list_movies.json?limit=1";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
throw new Exception("Curl request failed: " . $e);
}
curl_close($curl);
$data = json_decode($response);
var_dump($data);
if (!$data) {
throw new Exception("JSON decode error: " . json_last_error_msg());
}
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
You're probably getting an empty response, so json_decode() is failing. You need to check for this, since an empty response doesn't necessarily trigger a curl error.
private function getFromApi($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
if($e = curl_error($curl)) {
throw new Exception("Curl request failed: " . $e);
}
curl_close($curl);
$data = json_decode($response);
if (!$data) {
throw new Exception("JSON decode error: " . json_last_error_msg());
}
if ($data->status != 'ok') {
throw new Exception("API request failed. Error was: " . $data->status_message);
}
return $data->data;
}
Also, there's no need to use else if the if block throws, since it never returns.
I am following this part of the documentation: http://developers.marketo.com/rest-api/assets/tokens/ and I always get the following an error: Fields cannot be empty.
Have anyone make it worked?
public function create_token($folder_id,$name,$content,$folder_type = 'Program')
{
$folder_id = intval($folder_id);
$endpoint = 'rest/asset/v1/folder/'.$folder_id.'/tokens';
$body = new stdClass();
$body->folderType = $folder_type;
$body->name = $name;
$body->type = 'rich text';
$body->value = $content;
$body_encoded = json_encode($body);
echo $url = $this->url . $endpoint . ".json?access_token=" . self::$token;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body_encoded);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response);
}
The reason for the Content-Type header was a suggestion from Marketo: https://www.screencast.com/t/CL5ZtPo1o
This is the answer from the request I keep getting:
object(stdClass)#1934 (4) {
["success"]=>
bool(false)
["warnings"]=>
array(0) {
}
["errors"]=>
array(4) {
[0]=>
object(stdClass)#1935 (2) {
["message"]=>
string(20) "name cannot be null."
["code"]=>
string(3) "701"
}
[1]=>
object(stdClass)#1936 (2) {
["message"]=>
string(20) "type cannot be null."
["code"]=>
string(3) "701"
}
[2]=>
object(stdClass)#1937 (2) {
["message"]=>
string(101) "Token type is either null, blank or invalid. Please refer to the documentation for valid token types."
["code"]=>
string(3) "701"
}
[3]=>
object(stdClass)#1938 (2) {
["message"]=>
string(21) "value cannot be null."
["code"]=>
string(3) "701"
}
}
["requestId"]=>
string(16) "11d1#15b49284636"
}
You don't have to post token fields as JSON object: json_encode($body)
Fields are passed as request parameters or as a regular form
This request with works well for me:
POST https://123-FOO-456.mktorest.com/rest/asset/v1/folder/1039/tokens.json?value=TestTokenValue&folderType=Program&name=TestToken&type=text
In this case, you also don't have to specify content type Content-Type: x-www-form-urlencoded
I'm not PHP dev, but you can look here for examples how to post form data - PHP + curl, HTTP POST sample code?
I'd like to display the number of likes for my Facebook page on my website. The previous method I used isn't working anymore since a couple of days.
When I call the Facebook graph API like this:
https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/549585444&format=json
It gives me the following output (fictional example):
[{"url":"http:\/\/www.facebook.com\/549585444","normalized_url":"http:\/\/www.facebook.com\/549585444","share_count":0,"like_count":122,"comment_count":0,"total_count":122,"click_count":0,"comments_fbid":null,"commentsbox_count":0}]
Now I like to echo the like count:
<?php
$fb_page = "549585444";
$url = "https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/".$fb_page."&format=json";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_returned = curl_exec($curl);
curl_close($curl);
$json_returned = json_decode($json_returned, true);
echo $json_returned['like_count'];
?>
But the number doesn't appear. Any idea why?
As you can see in the JSON output, the answer is wrapped in an array:
array(1) {
[0]=>
array(9) {
["url"]=>
string(33) "http://www.facebook.com/549585444"
["normalized_url"]=>
string(33) "http://www.facebook.com/549585444"
["share_count"]=>
int(0)
["like_count"]=>
int(0)
["comment_count"]=>
int(0)
["total_count"]=>
int(0)
["click_count"]=>
int(0)
["comments_fbid"]=>
NULL
["commentsbox_count"]=>
int(0)
}
}
To get the number output, you'll have to get the first item in the array by changing this row:
echo $json_returned['like_count'];
To this:
echo $json_returned[0]['like_count'];
$curl = new Curl();
$data = 'Email='.urlencode('MYEMAIL#EMAIL.COM').'&Passwd='.urlencode('MYPASSWORD').'&accountType=GOOGLE&source=Google-cURL-Example&service=jotspot';
$curl->post('https://www.google.com/accounts/ClientLogin',$data);
//match authorization token
preg_match("!Auth=(.*)!",$curl->response,$match);
$auth = $match[1];
//set curl headers
$curl->set_headers(array(
'Content-Type: application/atom+xml; charset=utf-8',
'Host: sites.google.com',
'GData-Version: 1.4',
'Authorization: GoogleLogin auth='. trim($auth)));
//get a list of sites associated with my domain
$curl->get('https://sites.google.com/feeds/site/clevertechie.mygbiz.com');
//contains data returned by $curl->get();
echo $curl->response;
So instead of getting the list of sites from $curl->response, I get a message - "Content is not allowed in prolog." I've looked everywhere and haven't been able to find a solution, please help! Thanks! :)
This is the XML that is supposed to be returned by the response:
<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007' xmlns:sites='http://schemas.google.com/sites/2008' xmlns:gs='http://schemas.google.com/spreadsheets/2006' xmlns:dc='http://purl.org/dc/terms' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'>
<updated>2012-10-31T19:00:17.297Z</updated>
<app:edited xmlns:app='http://www.w3.org/2007/app'>2012-10-31T19:00:17.297Z</app:edited>
<title>My Site Title</title>
<summary>My Site Summary</summary>
<sites:siteName>my-site-title</sites:siteName>
<sites:theme>slate</sites:theme>
</entry>
I can't paste the source of "https://sites.google.com/feeds/site/clevertechie.mygbiz.com" because it can't be accessed directly without authorization token, which is specified in the headers. The only way to retrieve its data is by using the token in the headers which I've done. Instead of getting above XML, I'm getting "Content is not allowed in prolog".
var_dump of $curl:
object(Curl)#1 (11) { ["curl_resource":protected]=> resource(4) of type (Unknown) ["proxy":protected]=> bool(false)
["proxy_type":protected]=> NULL ["response"]=> string(33) "Content is not allowed in prolog." ["time"]=> float(249)
["info"]=> array(26) { ["url"]=> string(59) "https://sites.google.com/feeds/site/clevertechie.mygbiz.com"
["content_type"]=> string(24) "text/html; charset=UTF-8" ["http_code"]=> int(400) ["header_size"]=> int(676)
["request_size"]=> int(1935) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(20) ["redirect_count"]=> int(0)
["total_time"]=> float(0.249) ["namelookup_time"]=> float(0.015) ["connect_time"]=> float(0.046)
["pretransfer_time"]=> float(0.109) ["size_upload"]=> float(111) ["size_download"]=> float(33)
["speed_download"]=> float(132) ["speed_upload"]=> float(445) ["download_content_length"]=> float(-1)
["upload_content_length"]=> float(111) ["starttransfer_time"]=> float(0.249) ["redirect_time"]=> float(0)
["certinfo"]=> array(0) { } ["primary_ip"]=> string(14) "74.125.224.194" ["primary_port"]=> int(443)
["local_ip"]=> string(13) "192.168.1.133" ["local_port"]=> int(61985) ["redirect_url"]=> string(0) "" }
["error"]=> NULL ["custom_headers"]=> NULL ["cookie_file"]=> string(46) "cookies.txt"
["custom_curl_options":protected]=> array(3) { [47]=> int(1) [10015]=> string(111)
"Email=MYEMAIL&Passwd=MYPASSWORD&accountType=GOOGLE&source=Google-cURL-Example&service=jotspot"
[10023]=> array(4) { [0]=> string(49) "Content-Type: application/atom+xml; charset=utf-8"
[1]=> string(22) "Host: sites.google.com" [2]=> string(18) "GData-Version: 1.4" [3]=> string(320)
"Authorization: GoogleLogin auth=DQAAAMMAAAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" } } ["curl_options":protected]=> array(9) { [10018]=> string(74)
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1" [10016]=> string(22)
"http://www.google.com/" [13]=> int(60) [78]=> int(60) [19913]=> int(1) [52]=> int(1) [64]=> int(0) [81]=> int(0) [42]=> int(0) } }
$auth is just a string, its not supposed to be formatted as XML. I verified that there are no extra spaces or characters and it exactly matches the one returned by the first $curl->post request.
Leave the request type as a POST (with the content being the atom xml payload), set the content type to “application/atom+xml” but pass all of the oAuth as a GET, i.e. as escaped (urlEncoded) values on the URL query string.
I have problems with simple PHP function file_get_contents...
It shows NULL but it's enabled on the server so I don't know where is problem?
<?php
$url = "http://graph.facebook.com/oauth/access_token?client_id=(ID)&
client_secret=(PW)&grant_type=client_credentials";
$app_token = file_get_contents($url);
echo $app_token;
?>
(ID) and (PW) are appID and appSecret
Thanks in advance!
Personally, I would use php curl and https (http://developers.facebook.com/docs/reference/api/)
HTTP instead of HTTPS would output:
{
"error": {
"message": "client_secret must be passed over HTTPS",
"type": "OAuthException",
"code": 1
}
}
Please turn on error reporting during development. You may get:
Warning: file_get_contents(): Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? in /usr/local/apache2/htdocs/xxxxx/test12345.php on line 3
Use need to use HTTPS, and check what wrappers are enabled
On Windows you should see this in php.ini
extension=php_openssl.dll
Check the wrappers
<?php
var_dump(stream_get_wrappers());
?>
Which should give an output such as
array(12) {
[0]=>
string(5) "https"
[1]=>
string(4) "ftps"
[2]=>
string(13) "compress.zlib"
[3]=>
string(14) "compress.bzip2"
[4]=>
string(3) "php"
[5]=>
string(4) "file"
[6]=>
string(4) "glob"
[7]=>
string(4) "data"
[8]=>
string(4) "http"
[9]=>
string(3) "ftp"
[10]=>
string(4) "phar"
[11]=>
string(3) "zip"
Notice HTTPS is in the array.
A full example of how to get the token
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$app_token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id
. "&client_secret=" . $app_secret
. "&grant_type=client_credentials";
$response = file_get_contents($app_token_url);
$params = null;
parse_str($response, $params);
echo("This app's access token is: " . $params['access_token']);
?>
http://developers.facebook.com/docs/howtos/login/login-as-app/