Simple Yahoo Weather Api Not Working - api

I was using a simple code which includes a yahoo api code to get just the weather from my city and put in on my web page, however, i just read that yahoo public api is no longer working and i dont know how can a i get this code to work, i have a yahoo account, i created an api and i dont know how to proceed since here. If somebody can help me this is the code:
<?php
/*Clima*/
if(isset($_POST['zipcode']) && is_numeric($_POST['zipcode'])){
$zipcode = $_POST['zipcode'];
}else{
$zipcode = 'ARMA0056';
}
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=c');
$xml = simplexml_load_string($result);
//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');
if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$clima = <<<END
<span>{$current['temp']}°C</span>
END;
}
}else{
$clima = '<h1>No results found, please try a different zip code.</h1>';
}
/*Clima*/
?>

just replace http://weather.yahooapis.com with http://xml.weather.yahoo.com. credits to https://forum.rainmeter.net/viewtopic.php?f=13&t=23010

xml.weather.yahoo.com was the solution, but the URL does not seem to be working anymore. Im now using yahoos query to get the XML i.e."https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%3D2489314"
This seems to be the same XML with the exception of "results" added to the tree.

Yahoo recently updated the way they handle requests. It used to be just over any connection, but now to make it more secure and easier to handle, they recently opted into sending all requests over OAuth1. Use the sample code they provide on their page and get the information from the request over JSON.
See https://developer.yahoo.com/weather/ for more information.

YAHOO changed some rules about api;
I made following class working for me... hope works for you;
$fcast=$phpObj->query->results->channel->item->forecast; change this line for other items...
<?php
date_default_timezone_set('CET');
class weatherfc{
public $result;
function weather($city){
$BASE_URL = "http://query.yahooapis.com/v1/public/yql";
$yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="'.$city.'") and u="c"';
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
//var_dump($phpObj);
$weatherd='<div> Weather In '.$city.'<br>';
$fcast=$phpObj->query->results->channel->item->forecast;
foreach($fcast as $witem){
$fdate=DateTime::createFromFormat('j M Y', $witem->date);
$weatherd.= '<div class="days">';
$weatherd.= '<div class="item"><div>'.$fdate->format('d.m').' '.$witem->day.'</div><div class="image" style="width:90px !important; height:65px !important;"><img src="http://us.i1.yimg.com/us.yimg.com/i/us/nws/weather/gr/'.$witem->code.'d.png" width=90></div></div>';
$weatherd.= '<div><span>'.$witem->high.'°C</span>';
$weatherd.= '<span>'.$witem->low.'°C</span></div></div>';
};
$this->result=$weatherd;
}
}
$h= new weatherfc;
$h->weather("Antalya,Turkey");
echo $h->result;
?>
<style>
.days{
width:90px;
font-size:12px;
float:left;
font-family:Arial, Helvetica, sans-serif;
border:#999 1px dotted;
}
</style>

Related

How to work with youtube api V3

I need help with youtube API V3.
as when on the browser I type:
https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=Titanic%201997%20Official%20Trailer&key=
it's show return values.
However I am trying to collect the array from php.
How can I use GET https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=1&q=Titanic%201997%20Official%20Trailer&key= in php so I get the result in php?
or is there any option to get the search result in a rss feed format.
Thanks in advance
Make a simple video search on YouTube API and you will get video title, description, video id and image source so best approach full code is given below.
<?php
error_reporting(0);
$search = "Search Query"; // Search Query
$api = "YouTube API Key"; // YouTube Developer API Key
$results = 10; // Max results
$link = "https://www.googleapis.com/youtube/v3/search?safeSearch=moderate&order=relevance&part=snippet&q=".urlencode($search). "&maxResults=$results&key=". $api;
$video = file_get_contents($link);
$video = json_decode($video, true);
foreach ($video['items'] as $data){
$title = $data['snippet']['title'];
$description = $data['snippet']['title'];
$vid = $data['id']['videoId'];
$image = "https://i.ytimg.com/vi/$vid/default.jpg";
// Output Title/Description/Image URL If Video ID exist
if($vid){
echo "Title: $title<br />Description: $description<br />Video ID: $vid<br />Image URL: $image<hr>";
}
}
?>

Youtube Next Previous Pagination with Json

I am getting nextPageToken from json result but still didn't work. Not no where problem exist, can anyone plz look into this and rectify and help me in this issue.
`
$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&contentDetail&channelId= {$channelID}&type=video&maxResults=2&key={myAPiKey}");
$result = json_decode($jsonURL, true);
foreach ($result['items'] as $searchResult) {
$nPt = $result['nextPageToken'];
$Tmburl = $searchResult['snippet']['thumbnails']['high']['url'];
$views = $searchResult['statistics']['viewCount'];
$date = $searchResult['snippet']['publishedAt'];
echo '<h3>'.$searchResult['snippet']['title'].'</h3>';
echo '<img src="'.$Tmburl.'"/>';
echo '<p>'.$searchResult['snippet']['description'].'</p>';
}
// Pagination
echo '<h1>next</h1>';
`
The Next - Previous Pagination not working. Even i m getting nextPageToken number but link not functional.
I got, Just send pageToken value in Json URL, and pagination work.

Update video with YOUTUBE google-api-php-client

I'm trying update the video metadata with Youtube API. The API which I'm using is google-api-php-client.
That API works perfectly in upload and delete processes, but when I want update the video info I don't know what parameters I have to use.
This is the code:
try
{
// Build the Needed Video Information
$snippet = new Google_VideoSnippet();
$snippet->setTitle($_POST['videoTitle']);
$snippet->setDescription($_POST['videoDescription']);
$snippet->setTags(array($_POST['videoTags']));
$snippet->setCategoryId(22);
// Set the Video Info and Status in the Main Tag
$video = new Google_Video();
$video->setSnippet($snippet);
// Send the video to the Google Youtube API
$created_file = $youtube->videos->update('snippet', $video, array(
WHAT PARAMETERS!!!???!!
));
// Get the information of the uploaded video
print_r($createdFile);
}
catch (Exception $ex)
{
echo $ex;
}
Someone knows this? ? i'd like keep using this API because all my aplication use it.
Thank you in advanced.
To update a video, first you need to use videos->list with id=video_id, then update the part intended, wrap all subparts till to the video itself into google objects, and send an update request. (We will work to make this simpler)
Here's an update tags sample which ultimately updates the video, you can use it.
/**
* This sample adds new tags to a YouTube video by:
*
* 1. Retrieving the video with "youtube.videos.list" method setting the "id" parameter
* 2. Appending new tags to Video Resource's snippet.tags[] list
* 3. Updating the video itself via youtube.videos.update API call, supplying a new video via a
* binary upload to replace the old one.
*
* #author Ibrahim Ulukaya
*/
// Call set_include_path() as needed to point to your client library.
require_once 'Google_Client.php';
require_once 'contrib/Google_YouTubeService.php';
session_start();
/* You can acquire an OAuth 2 ID/secret pair from the API Access tab on the Google APIs Console
<http://code.google.com/apis/console#access>
For more information about using OAuth2 to access Google APIs, please visit:
<https://developers.google.com/accounts/docs/OAuth2>
Please ensure that you have enabled the YouTube Data API for your project. */
$OAUTH2_CLIENT_ID = 'REPLACE ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE ME';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// YouTube object used to make all Data API requests.
$youtube = new Google_YoutubeService($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Check if access token successfully acquired
if ($client->getAccessToken()) {
try{
// REPLACE with the video ID that you want to update
$videoId = "VIDEO_ID";
// Create a video list request
$listResponse = $youtube->videos->listVideos("snippet",
array('id' => $videoId));
$videoList = $listResponse['items'];
if (empty($videoList)) {
$htmlBody .= sprintf('<h3>Can\'t find a video with video id: %s</h3>', $videoId);
} else {
// Since a unique video id is given, it will only return 1 video.
$video = $videoList[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// $tags is null if the video didn't have any tags, so we will check for this and
// create a new list if needed
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Construct the Google_Video with the updated tags, hence the snippet
$updateVideo = new Google_Video($video);
$updateSnippet = new Google_VideoSnippet($videoSnippet);
$updateSnippet->setTags($tags);
$updateVideo -> setSnippet($updateSnippet);
// Create a video update request
$updateResponse = $youtube->videos->update("snippet", $updateVideo);
$responseTags = $updateResponse['snippet']['tags'];
$htmlBody .= "<h3>Video Updated</h3><ul>";
$htmlBody .= sprintf('<li>Tags "%s" and "%s" added for video %s (%s) </li>',
array_pop($responseTags), array_pop($responseTags),
$videoId, $updateResponse['snippet']['title']);
$htmlBody .= '</ul>';
}
} catch (Google_ServiceException $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Video Updated</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>

The sample of FQL query in FB is incorrect. Someone has a correct sample?

The sample posted in the documentation, at:
http://developers.facebook.com/docs/reference/fql/
is incorrect and does not work. (php)
$fql_query_url = 'https://graph.facebook.com/'
. '/fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=me()'
. '&' . $access_token;
$fql_query_result = file_get_contents($fql_query_url);
=> there are two / : ...facebook.com//fql...
=> the word "&access_token" is missing.
However, even issuing the correct url, the function does not seem to return anything...
Here is the code I have been using:
(function is passed $id, like 12345678)
$Fb = new Facebook(array('appId'=>FB_API_ID,'secret'=>FB_API_SECRET));
$access_token = $Fb->getAccessToken();
$fql_query_url = "https://graph.facebook.com/fql?q=SELECT+uid2+FROM+friend+WHERE+uid1=".$id."&access_token=" . $access_token;
$resp = file_get_contents($fql_query_url);
$var = json_decode($resp, true);
$txt .= "<br /><b>FQL QUERY:</b><br />" . display_tree($var);
Someone made it???
This query seems to work for me when I run it in the browser. Are you sure you have a valid access token?
Can you try it from the Graph API Explorer? Here's the link.

Youtube API: losing data via curl in PHP?

I'm sure that this is likely a simple solution, but I can't see my error. I'm making an API call to youtube to get some basic information on a youtube video using the video's ID; specifically what I want is the (1) title, (2) description, (3) tags, and (4) thumbnail.
When I load an API url via my web browser, I see all the data. I don't want to paste the entire response in this question, but paste the following url in your browser and you'll see what I see: http://gdata.youtube.com/feeds/api/videos/_83A00a5mG4
If you look closely you'll see media:thumbnail, media:keywords, content, etc. Everything I want is there. Now the troubles...
When I load this same url through the following functions (which I copied from the Vimeo api...), the thumbnail and keywords simply aren't there.
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
// youtube_get_ID is defined elsewhere...
$request_url = "http://gdata.youtube.com/feeds/api/videos/" . youtube_get_ID($url);
$video_data = simplexml_load_string(curl_get($request_url));
These functions do give me a response with some data, but the keywords and thumbnail are missing. Could anyone please tell me why my thumbnail and keywords are missing? Thank you for any help!
Here's the link for documentation on this.
Here's a function I wrote:
function get_youtube_videos($max_number, $user_name) {
$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/users/' . $user_name . '/uploads?max-results=' . $max_number);
$server_time = $xml->updated;
$return = array();
foreach ($xml->entry as $video) {
$vid = array();
$vid['id'] = substr($video->id,42);
$vid['title'] = $video->title;
$vid['date'] = $video->published;
//$vid['desc'] = $video->content;
// get nodes in media: namespace for media information
$media = $video->children('http://search.yahoo.com/mrss/');
// get the video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$vid['length'] = $attrs['seconds'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$vid['thumb'] = $attrs['url'];
// get <yt:stats> node for viewer statistics
$yt = $video->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$vid['views'] = $attrs['viewCount'];
array_push($return, $vid);
}
return $return;
}
And here's the implementation:
$max_videos = 9;
$videos = get_youtube_videos($max_videos, 'thelonelyisland');
foreach($videos as $video) {
echo $video['title'] . '<br/>';
echo $video['id'] . '<br/>';
echo $video['date'] . '<br/>';
echo $video['views'] . '<br/>';
echo $video['thumb'] . '<br/>';
echo $video['length'] . '<br/>';
echo '<hr/>';
}