SimpleXML - "Node no longer exists" - php

I'm trying to get the video data from this youtube playlist feed and add the interesting data to an array and use that later, but as you can see from the feed some videolinks are "dead" and that results in problems for my code.
The error I get is "Node no longer exists" when I try to access $attrs['url']. I've tried for hours to find a way to check if the node exists before I access it but I have no luck.
If anyone could help me to either parse the feed some other way with the same result or create a if-node-exists check that works I would be most happy. Thank you in advance
$url = 'http://gdata.youtube.com/feeds/api/playlists/18A7E36C33EF4B5D?v=2';
$sxml = simplexml_load_file($url);
$i = 0;
$videoobj;
foreach ($sxml->entry as $entry) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$videoobj[$i]['url'] = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$videoobj[$i]['thumb'] = $attrs['url'];
$videoobj[$i]['title'] = $media->group->title;
$i++;
}

if ($media->group->thumbnail && $media->group->thumbnail[0]->attributes()) {
$attrs = $media->group->thumbnail[0]->attributes();
$videoobj[$i]['thumb'] = strval($attrs['url']);
$videoobj[$i]['title'] = strval($media->group->title);
}

SimpleXML's methods always return objects, which are themselves linked to the original document (some internal thingy related to libxml.) If you want to store that data for later use, cast it as a string, like this:
$videoobj[$i]['url'] = (string) $attrs['url'];
$videoobj[$i]['thumb'] = (string) $attrs['url'];
$videoobj[$i]['title'] = (string) $media->group->title;

Related

How can I update a YouTube Video? | PHP

I try update a YouTube Video. I use the function at the site https://developers.google.com/youtube/v3/code_samples/php#update_a_video and I try to copy this in my code but if I call listVideos(), I get Google_Service_YouTube_VideoListResponse but I need a Google_Service_YouTube_Video. How can I get it?
My PHP Code:
$youtube = new Google_Service_YouTube($client);
$videoid = "******Video ID********";
$new = "******* TEXT *********";
$videoinfo = $youtube->videos->listVideos('snippet', array('id' => $videoid));
$videoSnippet = $videoinfo[0]['snippet'];
$description = $videoSnippet['description'] . $new;
$videoSnippet['description'] = $description;
$youtube->videos->update("snippet", $videoSnippet);
The Error:
: Uncaught TypeError: Argument 2 passed to
Google_Service_YouTube_Resource_Videos::update() must be an instance of
Google_Service_YouTube_Video, instance of
Google_Service_YouTube_VideoSnippet given, called in
P:\Apache24\htdocs\*********** on line 232 and defined in
P:\Apache24\htdocs\*******\Google Api System\vendor\google\apiclient-
services\src\Google\Service\YouTube\Resource\Videos.php:309
Stack trace:
0 P:\Apache24\htdocs\*********: Google_Service_YouTube_Resource_Videos-
>update('snippet', Object(Google_Service_YouTube_VideoSnippet ))
1 P:\Apache24\htdocs\********\*********\index.php(438):
require('P:\\Apache24\\htd...')
you have to use
$video = $listResponse[0];
$updateResponse = $youtube->videos->update("snippet", $video);
since in the documentation
// Since the request specified a video ID, the response only
// contains one video resource.
$video = $listResponse[0];
$videoSnippet = $video['snippet'];
$tags = $videoSnippet['tags'];
// Preserve any tags already associated with the video. If the video does
// not have any tags, create a new list. Replace the values "tag1" and
// "tag2" with the new tags you want to associate with the video.
if (is_null($tags)) {
$tags = array("tag1", "tag2");
} else {
array_push($tags, "tag1", "tag2");
}
// Set the tags array for the video snippet
$videoSnippet['tags'] = $tags;
// Update the video resource by calling the videos.update() method.
$updateResponse = $youtube->videos->update("snippet", $video);

Instagram JSON avatar extraction PHP

I want to extract the profile_picture of any instagram user from the JSON url: https://www.instagram.com/just/media/ with PHP and print it out. I've tried:
$instaJSONUrl = 'https://www.instagram.com/just/media/';
$json = file_get_contents($instaJSONUrl);
$json_data = json_decode($json, true);
echo $json_data["profile_picture"];
Not working.. If I print out the $json only, I get:
{status":"ok","items":[],"more_available":false}
Meaning that the problem is with reading the URL. Does this mean I need access token, because I don't want to use one, as I already can get the profile image URL when I open https://www.instagram.com/just/media/ from my browser.
This will result in an array of users and their picture profile links.
<?php
$instaJSONUrl = 'https://www.instagram.com/just/media/';
$json = file_get_contents($instaJSONUrl);
$json_data = json_decode($json, true);
$users = array();
foreach($json_data['items'] as $item)
foreach($item['comments'] as $comment)
foreach($comment as $profile)
$users[$profile['from']['username']] = $profile['from']['profile_picture'];
print_r($users);
Managed to do it via accessing the meta tags directly, and specifically the <meta property="og:image" tag, with the following:
libxml_use_internal_errors(true);
$c = file_get_contents($instaURL);
$d = new DomDocument();
$d->loadHTML($c);
$xp = new domxpath($d);
and then I can print out the image url with:
foreach ($xp->query("//meta[#property='og:image']") as $el) {
echo $el->getAttribute("content");
}
You can even use it to access other properties, such as og:url and og:description for the specific Instagram user.
This is for all those people who needs to access & get Instagram user data (basic: profile_image, profile_url, profile_description, etc.), without dealing with Instagram's API.

Namespace in MRSS feed using simplexml PHP Script

Tried to research what I'm doing wrong here, but no luck so far. I want to pull the links and URLs in this MRSS feed using this script, but it's not working. Thought all I needed to do was use namespaces to get the child elements out, but no luck:
<?php
$html = "";
$url = "http://feeds.nascar.com/feeds/video?command=search_videos&media_delivery=http&custom_fields=adtitle%2cfranchise&page_size=100&sort_by=PUBLISH_DATE:DESC&token=217e0d96-bd4a-4451-88ec-404debfaf425&any=franchise:%20Preview%20Show&any=franchise:%20Weekend%20Top%205&any=franchise:Up%20to%20Speed&any=franchise:Press%20Pass&any=franchise:Sprint%20Cup%20Practice%20Clips&any=franchise:Sprint%20Cup%20Highlights&any=franchise:Sprint%20Cup%20Final%20Laps&any=franchise:Sprint%20Cup%20Victory%20Lane&any=franchise:Sprint%20Cup%20Post%20Race%20Reactions&any=franchise:All%20Access&any=franchise:Nationwide%20Series%20Qualifying%20Clips&any=franchise:Nationwide%20Series%20Highlights&any=franchise:Nationwide%20Series%20Final%20Laps&any=franchise:Nationwide%20Series%20Victory%20Lane&any=franchise:Nationwide%20Series%20Post%20Race%20Reactions&any=franchise:Truck%20Series%20Qualifying%20Clips&any=franchise:Truck%20Series%20Highlights&any=franchise:Truck%20Series%20Final%20Laps&any=franchise:Truck%20Series%20Victory%20Lane&any=franchise:Truck%20Series%20Post%20Race%20Reactions&output=mrss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces
for($i = 0; $i < 50; $i++){ // will return the 50 most recent videos
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$pubDate = $xml->channel->item[$i]->pubDate;
$description = $xml->channel->item[$i]->description;
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$url = $xml->channel->item[$i]->children($namespaces['media'])->url;
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p>
<iframe width='480' height='270' src='http://link.brightcove.com/services/player/bcpid3742068445001?bckey=//my API token goes here &bctid=$titleid&autoStart=false' frameborder='0'></iframe><hr/>";/* this embed code is from the youtube iframe embed code format but is actually using the embedded Ooyala player embedded on the Campus Insiders page. I replaced any specific guid (aka video ID) numbers with the "$guid" variable while keeping the Campus Insider Ooyala publisher ID, "eb3......fad" */
}
echo $html;
?>
I take it this isn't the right approach:
$url = $xml->channel->item[$i]->children($namespaces['media'])->url;
What am I doing wrong here?
Thanks for any and all help!
MD
SimpleXML is deceptively named as it is more difficult to use than DOMDocument or the other PHP XML extensions. To get the URL, you'll need to access the url attribute of the media:content node:
<media:content duration="95" medium="video" type="video/mp4"
url="http://brightcove.meta.nascar.com.edgesuite.net/vod/etc"/>
Target the first <media:content> node using
$xml->channel->item[$i]->children($namespaces['media'])->content[0]
and get its attributes:
$m_attrs =
$xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
You can then access the url attribute:
echo "URL: " . $m_attrs["url"] . "\n";
Your code should thus be:
$titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
$m_attrs = $xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
$url = $m_attrs["url"];
$html .= "<h3>$title</h3>$description<p>$pubDate<p>$link<p>Video ID: $titleid<p> (etc.)";

Youtube Api to get video description with video id

I am trying to get discriptiobn from youtube using api .... but i dont no where am i wrong its not getting for single video . but if i try playlist its working fine, not with video id
Here is my code
error_reporting(E_ALL);
$feedURL = 'https://gdata.youtube.com/feeds/api/playlists/'.$id.'?v=2&prettyprint=true';
$sxml = simplexml_load_file($feedURL);
echo $feedURL.'</br>';
foreach ($sxml->entry as $entry)
{
echo $media->group->description;
}
Above code is working with playlist ... but if i try one video its not working:
error_reporting(E_ALL);
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/'.$id.'?v=2&alt=json&prettyprint=true';
$sxml = simplexml_load_file($feedURL);
echo $feedURL.'</br>';
foreach ($sxml->entry as $entry)
{
echo $media->group->description;
}
If you call YouTube api with 'alt=json' parameter, the response will be formatted as JSON not XML. So you should use:
$response = json_decode(file_get_contents('... API URL ...'), true);
And then 'description' can be accessed with:
$response['entry']['media$group']['media$description']['$t']

how to get description of youtube video details [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have you tube video link:
example:http://www.youtube.com/watch?v=EF5FnKTsIbc&feature=youtube_gdata_player
i want to get description and video title and image of this link using php,how do it?
Here is the code, I tested it and works great.
Thanks for IBM Developer network
You can see the entire code here.
http://www.ibm.com/developerworks/xml/library/x-youtubeapi/
USAGE
// For the video >>> youtube.com/watch?v=37l11UzbvvA
// Video id = 37l11UzbvvA;
$vid="37l11UzbvvA";
// set video data feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/videos/' . $vid;
// read feed into SimpleXML object
$entry = simplexml_load_file($feedURL);
$video = parseVideoEntry($entry);
echo $video->title;
Function > parseVideoEntry()
// function to parse a video <entry>
function parseVideoEntry($entry) {
$obj= new stdClass;
// get author name and feed URL
$obj->author = $entry->author->name;
$obj->authorURL = $entry->author->uri;
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
$obj->title = $media->group->title;
$obj->description = $media->group->description;
// get video player URL
$attrs = $media->group->player->attributes();
$obj->watchURL = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[0]->attributes();
$obj->thumbnailURL = $attrs['url'];
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$obj->length = $attrs['seconds'];
// get <yt:stats> node for viewer statistics
$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$obj->viewCount = $attrs['viewCount'];
// get <gd:rating> node for video ratings
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$obj->rating = $attrs['average'];
} else {
$obj->rating = 0;
}
// get <gd:comments> node for video comments
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->comments->feedLink) {
$attrs = $gd->comments->feedLink->attributes();
$obj->commentsURL = $attrs['href'];
$obj->commentsCount = $attrs['countHint'];
}
// get feed URL for video responses
$entry->registerXPathNamespace('feed', 'http://www.w3.org/2005/Atom');
$nodeset = $entry->xpath("feed:link[#rel='http://gdata.youtube.com/
schemas/2007#video.responses']");
if (count($nodeset) > 0) {
$obj->responsesURL = $nodeset[0]['href'];
}
// get feed URL for related videos
$entry->registerXPathNamespace('feed', 'http://www.w3.org/2005/Atom');
$nodeset = $entry->xpath("feed:link[#rel='http://gdata.youtube.com/
schemas/2007#video.related']");
if (count($nodeset) > 0) {
$obj->relatedURL = $nodeset[0]['href'];
}
// return object to caller
return $obj;
}
As Notified By Lothar Here is the Json Link,
You can parse this JSON data easily using json_decode
note: json_decode function works on PHP>=5.2.0
http://gdata.youtube.com/feeds/api/videos/[VIDEO_ID]?v=2&alt=jsonc
For Example
http://gdata.youtube.com/feeds/api/videos/37l11UzbvvA?v=2&alt=jsonc
The code below is a direct copy-paste from a script of mine. Not sure if it still works. You can give it a shot.
<?php
$id = '38z8TPtT1BE';
$url = "http://gdata.youtube.com/feeds/api/videos/$id?v=2&alt=json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
print_r(json_decode($output));
?>
Youtube APIs documentation is your bible. You will get all that you want in there. The link is what #ceejayoz gave in the comments section.
PS: Welcome to SO, and next time you have any problem, put up what you have already done. People here would surely help you out.

Categories