php SimpleXML - “节点不再存在”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2502038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SimpleXML - "Node no longer exists"
提问by Andreas Norman
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.
我正在尝试从这个 youtube 播放列表提要中获取视频数据,并将有趣的数据添加到一个数组中,稍后再使用,但正如您从提要中看到的,一些视频链接已“失效”,这导致我的代码出现问题。
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.
当我尝试访问 $attrs['url'] 时,我得到的错误是“节点不再存在”。我已经尝试了几个小时来找到一种在访问节点之前检查节点是否存在的方法,但我没有运气。
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
如果有人可以帮助我以相同的结果以其他方式解析提要,或者创建一个有效的 if-node-exists 检查,我会非常高兴。先感谢您
$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++;
}
回答by Bj?rn
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);
}
回答by Josh Davis
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:
SimpleXML 的方法总是返回对象,这些对象本身链接到原始文档(一些与 libxml 相关的内部事物)。如果要存储该数据以供以后使用,请将其转换为字符串,如下所示:
$videoobj[$i]['url'] = (string) $attrs['url'];
$videoobj[$i]['thumb'] = (string) $attrs['url'];
$videoobj[$i]['title'] = (string) $media->group->title;

