我有一个简单的PHP DOM解析器的问题。我基本上要刮一个目录网站的图像和他们的标题。
该网站是必须刮http://pinesite.com.
我已经提出了以下代码来完成它(这将通过AJAX调用):<?php
include ('simple_html_dom.php');
$function = $_GET['function'];
switch($function) {
case 'subcat':
$maincat = $_GET['cat'];
$url = "http://www.pinesite.com/meubelen/index.php?".$maincat."&lang=de";
$html = file_get_html($url);
$data = $html->find('.box_166_content .act_path li a');
$output ="";
foreach ($data as $subcat) {
$title = $subcat->plaintext;
$href = $subcat->href;
$link['title'] = $title;
$link['href'] =substr($href,10);
$output[] = $link;
}
echo json_encode($output);
$html->clear();
unset($html);
unset($url);
break;
case 'images':
$subcat = $_GET['subcat'];
$url = "http://www.pinesite.com/meubelen/index.php?".$subcat;
$html = file_get_html($url);
$iframe = $html->find('#the_iframe',0);
$url2 = $iframe->src;
$html->clear();
unset($html);
$html2 = file_get_html("http://www.pinesite.com/meubelen/".$url2);
$titles = $html2->find('p');
$images = $html2->find('img');
$output='';
$i=0;
foreach ($images as $image) {
$item['title'] = $titles[$i]->plaintext;
$item['thumb'] = $image->src;
$item['image'] = str_replace('thumb_','',$image->src);
$output[] = $item;
$i++;
}
echo json_encode($output);
break;
}
?>
这就是"functions"文件,不起作用的部分是最后一个。
我不知道这里出了什么问题,所以我在一个单独的文件中测试了它(最后一个案例)(我把它从iFrame获得的URL(那部分确实有效):
<?php
include_once "simple_html_dom.php";
$fullurl = "http://www.pinesite.com/meubelen/prog/browse.php?taal=nl&groep=18&subgroep=26";
$html = file_get_html($fullurl);
$titles = $html->find('p');
$images = $html->find('img');
$output='';
$i=0;
foreach ($images as $image) {
$item['title'] = $titles[$i]->plaintext;
$item['thumb'] = $image->src;
$item['image'] = str_replace('thumb_','',$image->src);
$output[] =$item;
$i++;
}
echo json_encode($output);
?>
就像我说的,第一部分应该返回与第二部分相同的内容(如果您添加?function=images&subcat=dichte-kast),但它没有。我猜这是因为我多次使用解析器。
有谁能给我一个建议吗?问题在于您的$url2
变量包含html实体,当您将其连接到根url时,结果不是一个有效的url。因此,file_get_html()
函数不会检索您期望的url(以及数据),而是一些不同的东西。
html_entity_decode()是一个快速解决问题的方法,但您可能也需要仔细阅读调试。它可以像将var_dump();
应用于您正在使用的每个变量一样简单,并查看输出与您期望的输出不同的地方。
您可能还需要检查一些安全问题。写$subcat = $_GET['sub_cat']
并不比直接使用$_GET['sub_cat']
安全。
我不确定我完全理解这个问题,但从我能收集到的是,你正试图从一个给定的网页抓取一些图像和它们相关的标题,然后保存它们?如果是这样的话,那么这里有一些值得思考的东西。(很抱歉不能更具体)。
使用file_get_contents抓取HTML内容。
$html = file_get_contents('www.someurl.com');
然后preg_match()所有图像标记和您可能需要的其他数据。有很多关于如何使用preg_match
匹配IMG标签的SRC属性的信息 $matches = preg_match('<img>*<'/img>', $html); # this is a guess
一旦你有一个图像标签的集合作为一个数组,然后使用curl保存图像
http://www.edmondscommerce.co.uk/php/php-save-images-using-curl/
我认为你的问题是把html内容从你想要的内容中剥离出来