First element of JSON (fanart.tv API) - php

I've been working of a project of mine, just to learn a bit more about PHP and JSON handling. I worked with the Fanart.tv API now and get everything up and running as I want, but I've run into some issues. I want to get the FIRST array in the JSON file, but everything I've tried so far doesn't do the trick.
Anyone wants to help me?
Here's the JSON file I'm trying to work with;
{"Eminem":{"mbid_id":"b95ce3ff-3d05-4e87-9e01-c97b66af13d4","artistbackground":[{"id":"14795","url":"http://assets.fanart.tv/fanart/music/b95ce3ff-3d05-4e87-9e01-c97b66af13d4/artistbackground/eminem-4ed3e35d6f3da.jpg","likes":"3"}
This is my code from my PHP file that actually works;
$img = $json->Eminem->artistbackground[0]->url;
However, I want to print the image and echo the name of the artist - in this case "Eminem". I've tried with "$json[0]" and just "[0]", but then I just get error messages. Anyone know how this can be done, reading the JSON file? I get the script updating the ID in the URL ($mbid) from MusicBrainz automatically, so if it is another artist than Eminem I read the JSON file from - my code doesn't work.
This is my PHP code so far;
$backgroundURL = 'http://api.fanart.tv/webservice/artist/a93e666f14a34d979b3e3617eab2f340/'.$mbid.'/json/artistbackground/1/1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $backgroundURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; curl)");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json = curl_exec($ch);
curl_close($ch);
$json = json_decode($json);
$bg = $json->Eminem->artistbackground[0]->url;
echo '<img src="'.$bg.'" height="540" width="960">'
As long as the JSON file is for the artist Eminem, it works. As soon as I get another artist, it doesn't so i need the first element in the JSON file in the $bg string.
Anyone knows how to do this?
Thanks for the help!

current() function returns value of the current key (first):
$json = json_decode($json);
$first = current($json);
$bg = $first->artistbackground[0]->url;

Related

Open a URL with a PHP within it using cURL

I am trying to fetch data from a URL using cURL...this is something I would be able to do but the URL that I want to fetch data from has a section of php code within it - i.e. the URL is populated using a values generated by an earlier section of code.
I want to access the URL, take the figures out of it and then plug those figures into something else. At the minute I am hitting a bit of a roadblock as the php doesn't populate the URL...any ideas?
The code I am using is:
$url = "https://*START OF API ADDRESS*<?php echo $request_ids; ?>*END OF API ADDRESS*";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
//var_dump(json_decode($result, true));
$rates = json_decode($result, true);
// Save result
$rates['last_updated'] = time();
file_put_contents($file, json_encode($rates));
}

php curl_setopt() returns json data with "1" on end

so I have a curl_setopt that is pulling a json file just fine with php. It does this with one exception, at the end of the json data there is a one (1) on the end after the last '}'. This "1" is not apparent in the url call by itself without using curl though. So it seems my curl_setopt is not configured properly. Can someone help with this?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $domain.$args);
curl_setopt($ch, CURLOPT_HEADER, false);
$json = curl_exec($ch);
curl_close($ch);
the $domain.$args is working fine as I can echo out this variable setup and produce the json manually via browser without the 1.
appreciate the help
/** edit after suggestions **/
I tried the suggestion below of adding:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
this just ended up changing the entire json output, not just adding a "1" on the end of the response:
"{\"data\":[{\"Name\":\"A3\",\"SeoName\":\"a3\"},{\"Name\":\"A4\",\"SeoName\":\"a4\"},{\"Name\":\"A5\",\"SeoName\":\"a5\"},{\"Name\":\"A6\",\"SeoName\":\"a6\"},{\"Name\":\"A7\",\"SeoName\":\"a7\"},{\"Name\":\"A8\",\"SeoName\":\"a8\"},{\"Name\":\"allroad\",\"SeoName\":\"allroad\"},{\"Name\":\"Q5\",\"SeoName\":\"q5\"},{\"Name\":\"Q5 hybrid\",\"SeoName\":\"q5-hybrid\"},{\"Name\":\"Q7\",\"SeoName\":\"q7\"},{\"Name\":\"R8\",\"SeoName\":\"r8\"},{\"Name\":\"RS 5\",\"SeoName\":\"rs-5\"},{\"Name\":\"RS 7\",\"SeoName\":\"rs-7\"},{\"Name\":\"S4\",\"SeoName\":\"s4\"},{\"Name\":\"S5\",\"SeoName\":\"s5\"},{\"Name\":\"S6\",\"SeoName\":\"s6\"},{\"Name\":\"S7\",\"SeoName\":\"s7\"},{\"Name\":\"S8\",\"SeoName\":\"s8\"},{\"Name\":\"SQ5\",\"SeoName\":\"sq5\"},{\"Name\":\"TT\",\"SeoName\":\"tt\"},{\"Name\":\"TTS\",\"SeoName\":\"tts\"}]}"
Use this:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Fix but not ideal is to substr() it to strip out the 1.
substr($result, 0, strlen($result) - 1);

Using CURL to play Youtube videos

I'm using CURL to get Youtube page like this:
$url = "https://www.youtube.com/watch?v=jyPnQw_Lqds";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
echo $curl_scraped_page;
It seems the video doesn't play, I don't know why. I found a script which solves this problem by setting the data as format json and then decodes the json as plain html like this:
$youtube = "http://www.youtube.com/oembed?url=" . $url. "&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$result = json_decode($return, true);
echo $result['html'];
Im trying to "merge" this two scripts to function as one. I put the scripts together like this:
PHPFiddle EXAMPLE, CLICK THE RUN(F9) BUTTON
As you can see the video in the top doesn't play. If you scroll down to the bottom you will see another video (which is the video echoed by the JSON) this one can actually be played.
How do I get the upper(top) video to play? I was thinking about first "finding" the "object" and then format as json etc. But Im afraid this will mess up the page.

Help w/ Retrieving XML via cURL

I've run into trouble with the following php code:
<?php
$url = "http://api.ean.com/ean-services/rs/hotel/v3/list? minorRev=1&cid=55505&apiKey=58x5kuujub8xbb5tzv3a2a8q&locale=en_US&currencyCode=USD&xml= <HotelListRequest><destinationString>Seattle</destinationString> <arrivalDate>08/01/2011</arrivalDate><departureDate>08/03/2011</departureDate><RoomGroup> <Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup> <numberOfResults>1</numberOfResults></HotelListRequest>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$contents = curl_exec ($ch);
echo $contents;
curl_close($ch);
?>
The problem is that $contents contains markup that's not XML at all, so I can't parse it. It's confusing b/c entering the URL in my browser's address bar will display the XML document, but I can't seem to get a valid XML doc w/ this code.
Here is a snippet of the string that gets returned:
{"HotelListResponse":{"customerSessionId":"0ABAA83D-4428-4913-0382-28FBB1901EFC","numberOfRoomsRequested":1,"moreResultsAvailable":true,"cacheKey":"-32344284:1303828fbb1:-1ef9","cacheLocation":"10.186.168.61:7305","HotelList":{"#size":"1","HotelSummary":{"#order":"0"
Could someone explain to me where I'm going wrong?
Thx.
Instead of trying to get XML, which may not be provided, you could always work with what you have, which appears to be JSON.
$response = json_decode( $contents, true );
This will give you an associative array of your data, which can be much easier to work with.
Try to remove spaces: "/v3/list? minorRev=1" -> "/v3/list?minorRev=1"
Make your URL correct, like
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?type=xml&minorRev=1&cid=55505&apiKey=58x5kuujub8xbb5tzv3a2a8q&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3CdestinationString%3ESeattle%3C/destinationString%3E%3CarrivalDate%3E08/01/2011%3C/arrivalDate%3E%3CdepartureDate%3E08/03/2011%3C/departureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C/numberOfAdults%3E%3C/Room%3E%3C/RoomGroup%3E%20%3CnumberOfResults%3E1%3C/numberOfResults%3E%3C/HotelListRequest%3E';
Add option to accept xml only -- in browser we have such header -- in curl -- no:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
PROFIT!!!

Updating Twitter background via API

I'm having a little trouble updating backgrounds via Twitter's API.
$target_url = "http://www.google.com/logos/11th_birthday.gif";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $html), 'POST');
When I try to pull the raw data via cURL or file_get_contents, I get this...
Expectation Failed The expectation given in the Expect request-header
field could not be met by this server.
The client sent
Expect: 100-continue but we only allow the 100-continue expectation.
OK, you can't direct Twitter to a URL, it won't accept that. Looking around a bit I've found that the best way is to download the image to the local server and then pass that over to Twitter almost like a form upload.
Try the following code, and let me know what you get.
// The URL from an external (or internal) server we want to grab
$url = 'http://www.google.com/logos/11th_birthday.gif';
// We need to grab the file name of this, unless you want to create your own
$filename = basename($url);
// This is where we'll be saving our new file to. Replace LOCALPATH with the path you would like to save the file to, i.e. www/home/content/my_directory/
$newfilename = 'LOCALPATH' . $filename;
// Copy it over, PHP will handle the overheads.
copy($url, $newfilename);
// Now it's OAuth time... fingers crossed!
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $newfilename), 'POST');
// Echo something so you know it went through
print "done";
Well, given the error message, it sounds like you should load the URL's contents yourself, and post the data directly. Have you tried that?

Categories