LoginSignup
4
5

More than 5 years have passed since last update.

対象のURLから特定の画像URLを取得するコード

Last updated at Posted at 2016-03-15

特定のページから特定のIDを付与した画像URLを取得したかったので作ってみた。

githubとか参考にしました。
https://github.com/pellcorp/opendb/blob/master/lib/site/amazon.class.php

これをどこかに書いたら使えるようになります。

func_get_image.php
<?php
/**
 * 特定URLの特定IDをつけた画像を取得
 */
function get_image_by_id( $url, $id ) {
        $img_url = "";
        if ( isset( $url ) && $url != "" && isset( $id ) && $id != "" ) {
                $pageBuffer = file_get_contents( $url );
                ob_start();
                ob_end_clean();
                if (preg_match_all("!<img [^>]*?id=\"$id\" [^>]*?src=\"([^\"]+)\"!s", $pageBuffer, $regs) ||
                           preg_match_all("!<img [^>]*?src=\"([^\"]+)\" [^>]*?id=\"$id\"!s", $pageBuffer, $regs)) {
                        $image = $regs[1];
                }
                $img_url = $image[0];
        }
        return $img_url;
}

使い方

<?php

include_once('func_get_image.php');
$url = "http://joy.ful.jp/"; // サンプル

$image_url = get_image_by_id( $url, "logo_img" );
?>
<img src="<?php echo $image_url; ?>" />

これで特定のURLから特定のIDが付与されたイメージが取得できる・・・はず。
改造すれば特定のaltとかtitleとかでもいけるとおもいます。

参考のURLをご覧いただけばいろいろできるかもしれません。

特定ページのHTMLがリニューアルされたらおしまいですけど・・・

4
5
2

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
4
5