是否有一个模拟Facebook“链接检测”的库?

时间:2009-12-08 17:30:50

标签: c# php asp.net facebook

我正在寻找一个库,可以在发布链接时“解析”像facebook这样的信息。但是,由于我不想重新发明轮子,有没有人知道图书馆或努力编写一个已经这样做的图书馆?

我已经包含了一个示例,以便您可以掌握我的意思,如果您不使用脸书。 http://lh4.ggpht.com/_zbED-KN_ZAI/Sx6LuDmZkVI/AAAAAAAADLs/mN7eFnzL1gE/s144/example.png

2 个答案:

答案 0 :(得分:6)

没有看到任何图书馆,但看起来很简单。我已经记下了一个可以帮助你的快速功能。我保持简单,您可能希望使用cURL来获取内容,进行一些错误处理等。

无论如何,这是我的两分钱:

<?php

function getLinkInfo($url)
{
    // Get target link html
    $html = file_get_contents($url);

    // Prepare the DOM document
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $dom->preserveWhiteSpace = false; 

    // Get page title
    $titles = $dom->getElementsByTagname('title');
    foreach ($titles as $title) {
        $linkTitle = $title->nodeValue;
    }

    // Get META tags
    $metas = $dom->getElementsByTagname('meta'); 

    // We only need description
    foreach ($metas as $meta) {
        if ($meta->getAttribute("name") == "description") {
            $linkDesc = $meta->getAttribute("content");
        }
    }

    // Get all images
    $imgs = $dom->getElementsByTagname('img'); 

    // Again, we need the first one only
    foreach ($imgs as $img) {
        $firstImage = $img->getAttribute("src");

        if (strpos("http://", $firstImage) === false) {
            $firstImage = $url . $firstImage; 
        }

        break;
    }

    $output = <<<HTML

    <div class="info">

        <div class="image"><img src="{$firstImage}" alt="{$linkTitle}" /></div>
        <div class="desc">
            <div class="title">{$linkTitle}</div>
            <div class="subtitle">{$url}</div>
            <div class="summary">{$linkDesc}</div>
        </div>

    </div>

HTML;

    return $output;
}

echo getLinkInfo("http://www.phpfour.com/");

答案 1 :(得分:1)

John Gruber a regex pattern可能有所帮助:

  

一个常见的编程问题:   识别任意的URL   字符串,其中“任意”   让我们同意我们的意思   非结构化的,例如电子邮件消息   或推特。