PHP file_get_contents
我在创建一个PHP脚本,其中,用户将提供一个网页链接,它将获取该网页的内容并根据其内容解析内容。PHP file_get_contents
例如,如果用户提供了一个YouTube链接:
http://www.youtube.com/watch?v=xxxxxxxxxxx
然后,它会抢关于该视频的基本信息
或者他们可能会提供一个VIMEO(缩略图,嵌入代码?)链接:
http://www.vimeo.com/xxxxxx
或者即使他们提供任何链接,没有附加的视频,如:
http://www.google.com/
它可以抓取页面标题或一些元内容。
我想我不得不使用file_get_contents,但我不完全确定如何在这种情况下使用它。
我不想找人编写整个代码,但可能会提供一些工具,以便我可以完成此操作。
也许Thumbshots或Snap已经有一些你想要的功能?
我知道那不是你正在寻找的东西,但至少对于可能方便的嵌入式东西来说。另外txwikinger已经回答了你的其他问题。但也许这有助于ypu。
file_get_contents()
会在这种情况下工作,假设您的php.ini中有allow_fopen_url
设置为true
。你会做什么是一样的东西:
$pageContent = @file_get_contents($url);
if ($pageContent) {
preg_match_all('#<embed.*</embed>#', $pageContent, $matches);
$embedStrings = $matches[0];
}
这就是说,file_get_contents()
不会给你太多的错误处理其它接收成功或失败的内容false
的方式。如果您希望对请求具有更丰富的控制权并访问HTTP响应代码,请使用curl函数(特别是curl_get_info
)查看响应代码,MIME类型,编码等。一旦通过curl或file_get_contents()
解析它以查找感兴趣的HTML的代码将是相同的。
使用HTTP包装函数调用file_get_contents(打开URL)后,变量$ http_response_header将填充响应头 – Greg 2009-09-05 23:20:38
我知道这个问题是相当古老的,但我会回答,以防万一有人打它寻找同样的事情。
为YouTube,Vimeo,Wordpress,Slideshare,Hulu,Flickr和许多其他服务使用oEmbed(http://oembed.com/)。如果不在列表中,或者你想让它更精确,您可以使用此:
http://simplehtmldom.sourceforge.net/
这是一个老的jQuery的PHP的,这意味着你可以使用HTML选择器来获取代码的部分(即:所有图像,获取div的内容,仅返回节点的文本(无HTML)内容等)。
你可以做这样的事情(可能更优雅的完成,但是这仅仅是一个例子):
require_once("simple_html_dom.php");
function getContent ($item, $contentLength)
{
$raw;
$content = "";
$html;
$images = "";
if (isset ($item->content) && $item->content != "")
{
$raw = $item->content;
$html = str_get_html ($raw);
$content = str_replace("\n", "<BR /><BR />\n\n", trim($html->plaintext));
try
{
foreach($html->find('img') as $image) {
if ($image->width != "1")
{
// Don't include images smaller than 100px height
$include = false;
$height = $image->width;
if ($height != "" && $height >= 100)
{
$include = true;
}
/*else
{
list($width, $height, $type, $attr) = getimagesize($image->src);
if ($height != "" && $height >= 100)
$include = true;
}*/
if ($include == true)
{
$images = $images . '<div class="theImage"><a href="'.$image->src.'" title="'.$image->alt.'"><img src="'.$image->src.'" alt="'.$image->alt.'" class="postImage" border="0" /></a></div>';
}
}
}
}
catch (Exception $e) {
// Do nothing
}
$images = '<div id="images">'.$images.'</div>';
}
else
{
$raw = $item->summary;
$content = str_get_html ($raw)->plaintext;
}
return (substr($content, 0 , $contentLength) . (strlen ($content) > $contentLength ? "..." : "") . $images);
}
试着问一个更直接的问题,如“我怎么找一部电影的缩略图在使用PHP的YouTube中“这可能会让人们更敏感。 – 2009-09-05 20:17:27