因此,我尝试使用标题PHP中提到的cURL来显示来自另一个页面的div (例如Kinguin)。现在我已经想出了一种方法来处理图像(简单的YT教程)和图像,但是我不能使用绑定了类的div来做到这一点。一些支持页面似乎把我引向了正确的方向,但过了一段时间,它似乎变得复杂起来。
是正确的方法,还是应该使用AJAX。
<?php
$curl = curl_init();
$search_string = "gta5";
$url = "https://www.kinguin.net/catalogsearch/result/index/?q=$search_string";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_COOKIE,true); //Verify cookies
$result = curl_exec($curl);
preg_match_all("!https://cdns.kinguin.net/media/catalog/category/cache/1/image/173x118/9df78eab33525d08d6e5fb8d27136e95/gta5_12.jpg!", $result,$matches);
$images = array_values(array_unique($matches[0]));
for ($i = 0; $i < count ($images); $i++){
echo "<div style='float: left; margin: 10 0 0 0; '> ";
echo "<img src='$images[$i]'><br />";
echo "</div>";
}
curl_close($curl);
?>
发布于 2018-07-04 05:43:08
为了解析div元素,可以使用解析器。外面有很多库。一个是SimpleHtml Dom。它具有如下选择器功能:
// Find all images
foreach($html->find('img') as $element) echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element) echo $element->href . '<br>';
一些JQuery选择器样式的php解析器也是可用的。一个是(但我还没有用过它):https://github.com/tburry/pquery
您也可以在前端站点采用AJAX的方式,但在这种情况下,您将不得不使用jsonp,因为域是不同的。您可以通过jsonp获取html,将其放入页面中的一个隐藏容器中以供临时使用,并解析来自该容器的数据。
我更喜欢在服务器端完成这项任务。原因是:
a) It will not put pressure on the client computer/device.
As the browser page will have to pull data from another domain.
b) You can cache the data in server.
c) Parsing is costly. In some device the browser may go irresponsive.
d) In serverside you will be able handle the exceptions(if any occurs, like page unavailable, html structure of that page got changed etc) better than in a client's browser.
发布于 2018-07-04 05:54:12
这里的解决方案实际上取决于你想要下载的内容。preg_match_all
是一个使用正则表达式的字符串匹配函数。你可以找到它的文档here,你可以用浏览器应用程序测试正则表达式,比如RegExr你调整后的preg_match_all
调用可能是这样的:
preg_match_all('@<div class="some-class">[^<]+</div>@', $result, $matches);
但是,由于您要下拉一个<div>
标记以及它的所有内容,因此可能需要查看DOMDocument之类的html解析库
$dom = new DOMDocument(); $dom->loadHTML($result);
foreach ($dom->getElementsByTagName('div') as $div) {
$class = $item->getAttribute("class");
if (strpos($class, 'some-class') !== false) {
echo "<div>";
echo $div->nodeValue;
echo "</div>";
}
}
如果您不想使用DOMDocument (可以理解,因为它更多地是为XML而设计的),那么可以尝试使用composer库。https://packagist.org/?query=html%20parser
https://stackoverflow.com/questions/51162878
复制相似问题