我有一个页面,可以自动从 MySQL 数据库中检索两个随机条目,并要求用户在每次刷新页面时对它们进行比较。如何自动将这两个字符串转换为它们的第一个谷歌图像结果?这是我到目前为止所拥有的:
<?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/
然后我简单地将这段 PHP 代码添加到我想要显示图片的 div 中:
<?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 像素),但这实际上非常适合我想要做的事情。如果您想检索非缩略图图片,那就是完全不同的蠕虫了。
关于javascript - 如何在我的页面上自动显示第一张 google 图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305942/