1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP+AjaxでHEAD内のOGP情報を取得する方法

Last updated at Posted at 2020-02-18

[PR] e-zines(イージンズ) - 新しいスタイルでトレンドをお送りする無料のメールマガジン

いろいろな技術系のブログにOGP情報の取得方法が載ってるのだけれど
キュレーションサイトによって記事のOGP記述方法が様々なので自分で書いてみた

適当なファイル GetOGP.php とかにして ajax から呼ぶとほぼほぼ取得できます
取得できないサイト(記事)があったらコメントに書いてくれれば直しますYO!

GetOGP.php
<?php
try {
    header('content-type: application/json; charset=utf-8');
    $url    = $_GET["url"];
    if (isset($url) and preg_match("/^https?:/", $url)) {
        $ctx    = stream_context_create(array(
            'http' => array(
                'method' => 'GET',
                'header' => 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36')
            )
        );
        $temp   = file_get_contents($url, false, $ctx);
        $temp   = mb_convert_encoding($temp, "UTF-8", "auto");
        preg_match('/(<head|<HEAD)(.*)(head>|HEAD>)/s', $temp, $head);
        $html   = $head[0];

        // ogp
        $ogp    = null;
        preg_match_all("<meta\s*property=[\"']og:([^\"']+)[\"']\s*content=[\"']([^\"']+)[\"']\s*>", $html, $ogp);
        for( $i = 0; $i < count($ogp[1]); $i++ ) {
            $result[$ogp[1][$i]] = $ogp[2][$i];
        }

        $ogp    = null;
        preg_match_all("<meta\s*content=[\"']([^\"']+)[\"']\s*property=[\"']og:([^\"']+)[\"']\s*>", $html, $ogp);
        for( $i = 0; $i < count($ogp[1]); $i++ ) {
            $result[$ogp[2][$i]] = $ogp[1][$i];
        }

        $ogp    = null;
        preg_match_all("<meta\s*name=[\"']og:([^\"']+)[\"']\s*content=[\"']([^\"']+)[\"']\s*>", $html, $ogp);
        for( $i = 0; $i < count($ogp[1]); $i++ ) {
            $result[$ogp[1][$i]] = $ogp[2][$i];
        }

        // twitter
        $twitter    = null;
        preg_match_all("<meta\s*name=[\"']twitter:([^\"']+)[\"']\s*content=[\"']([^\"']+)[\"']\s*>", $html, $twitter);
        for($i = 0; $i < count($twitter[1]); $i++) {
            $result2[$twitter[1][$i]] = $twitter[2][$i];
        }

        if (count($twitter[1]) == 0) {
            preg_match_all("<meta\s*content=[\"']([^\"']+)[\"']\s*name=[\"']twitter:([^\"']+)[\"']\s*>", $html, $twitter);
            for($i = 0; $i < count($twitter[1]); $i++) {
                $result2[$twitter[2][$i]] = $twitter[1][$i];
            }
        }

        if (!isset($result['title'])) {
            $result['title']    = $result2['title'];
        }
        if (!isset($result['url'])) {
            if (isset($result2['url'])) {
                $result['url']  = $result2['url'];
            } else {
                $result['url']  = $url;
            }
        }
        if (!isset($result['image'])) {
            if (isset($result2['image:src'])) {
                $result['image']    = $result2['image:src'];
            } else {
                $result['image']    = $result2['image'];
            }
        }
        if (!isset($result['description'])) {
            $result['description']  = $result2['description'];
        }
        if (!isset($result['site_name'])) {
            $result['site_name']    = $result2['site'];
        }

        $res    = [
            'title'         => str_replace('"', '”', $result['title']),
            'url'           => str_replace('http://', 'https://', $result['url']),
            'image'         => str_replace('http://', 'https://', $result['image']),
            'description'   => str_replace('"', '”', $result['description']),
            'site_name'     => str_replace('"', '”', $result['site_name']),
        ];

        // success
        echo json_encode($res);
    } else {
        // fail
        echo json_encode(['status' => 'error']);
    }
} catch (Exception $e) {
    // fail
    echo json_encode([
            'status' => 'fatal error:'.$e->getMessage(),
    ]);
}
?>

では、また

[PR] e-zines(イージンズ) - 新しいスタイルでトレンドをお送りする無料のメールマガジン

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?