簡體   English   中英

如何自動在頁面上顯示第一個Google圖片?

[英]How do I automatically display the first google image on my page?

我有一個頁面,該頁面會自動從MySQL數據庫中檢索兩個隨機條目,並在每次刷新頁面時要求用戶對其進行比較。 如何將這兩個字符串自動轉換為第一個Google圖片結果? 這是我到目前為止的內容:

<?php //I retrieve the names and group names here//
$firstpersonaName = (string) $row["personaName"];
$firstpersonaGroupName = (string) $row["groupName"];
    $firstpersonaGroupNameForGoogle = preg_split('( )', $firstpersonaGroupName);
?> //then convert any group names containing spaces into arrays here//

<?php  //then here I build the query that displays a google image page//
    $newname = '';
    foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
        $newname = $firstpersonaPartofGroupName . '+';
    }
    $newname = rtrim($newname, "+");
    echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch'; 
?>

這給了我類似的東西: https : //www.google.com/search?q=charlie+always+sunny&tbm=isch

那么,如何獲取該鏈接並將其轉換為第一張圖片的鏈接? 還是前幾對夫婦中的任何一個。 (在這種情況下: http : //cdn3.denofgeek.us/sites/denofgeekus/files/sunny_0.jpg

好的,這就是我最終要為每個查詢隨機生成兩張圖片的目的:

首先,我下載了該文件並將其添加到與網頁相同的目錄中: http : //simplehtmldom.sourceforge.net/

然后,我只是在想要顯示圖片的div中添加了此PHP代碼:

<?php
    // Include the php dom parser    
    include_once 'simple_html_dom.php';
    //build the google images query
    $newname = '';
    foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
        $newname = $firstpersonaPartofGroupName . '+';
    }
    $newname = rtrim($newname, "+");
    //echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch'; 
    $newname = "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';

    //use parser on queried page
    $html = file_get_html($newname);
    //echo $html;

    //create an array for all pics on page
    $picarray = array();
    $picurl = '';

    // Find all images 
    foreach($html->find('img') as $element) {
       //echo $element->src . '<br>';
       $picurl = $element->src;
       array_push($picarray,$picurl);
    }
    //then pick two random ones
    $picurl = $picarray[array_rand($picarray)];
    echo "<img src=" . $picurl . ">";
    $picurl = $picarray[array_rand($picarray)];
    echo "<img src=" . $picurl . ">";

?>

它們的分辨率很小(約150像素),但實際上與我想做的一樣很好。 如果您想獲取一個非縮略圖圖片,那是完全不同的蠕蟲罐頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM