【发布时间】:2013-07-12 08:48:27
【问题描述】:
我需要使用 url 的购物网站的标题和元标记以及图像标记。 这是我的代码,它使用亚马逊产品链接工作。但它不能像这样的网址:
- http://www.alternate.de/Synology/Synology+DS413,_NAS/html/product/1028780/?
- http://www.bonprix.de/produkt/baby-fleecejacke-hellgrau-meliert-958416/
我获取标签的代码:
$url ="http://rads.stackoverflow.com/amzn/click/B009T9QCWI";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
$returned_content = $data;
$doc = new \DOMDocument();
@$doc->loadHTML($returned_content);
$nodes = $doc->getElementsByTagName("title");
//$title = $nodes->item(0)->nodeValue;
$product_title = str_replace("'", " ", $title);
$xml=simplexml_import_dom($doc);
$images=$xml->xpath("//img");
$j=0;
foreach($images as $img) {
$host = explode(":",$img["src"]);
$ht = $host[0];
if ($ht == "http" || $ht == "https" ) {
$info = pathinfo($img["src"]);
if (array_key_exists('extension', $info)) {
$extension = $info["extension"];
}
if ($extension == "jpg" || $extension == "jpeg") {
$imagesrc[] = $img["src"];
$j++;
$image[] = $img["src"] ;
}
}
}
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++) {
$meta = $metas->item($i);
if ($meta->getAttribute('name') == 'description' || $meta->getAttribute('name') == 'Description') {
$description = $meta->getAttribute('content');
}
if ($meta->getAttribute('name') == 'keywords') {
$keywords = $meta->getAttribute('content');
}
}
if (empty($image)) {
$domarray[] = array('desc' => $description, 'title'=>$product_title);
print_r($domarray);
} else {
$domarray[] = array('img' =>$image, 'desc' => $description, 'title'=>$product_title);
print_r($domarray) ;
}
【问题讨论】:
-
您正在尝试在那里将 HTML 解析为 XML。请不要(stackoverflow.com/questions/1732348/…)我认为亚马逊有一个 API 可以以更可解析的方式获取您的信息(affiliate-program.amazon.com/gp/advertising/api/detail/…)。
-
@ToBe 请注意,使用了
loadHTML()。完全没问题 -
谢谢你。但我的目标不仅仅是亚马逊。亚马逊也可以使用这段代码。
-
您应该使用格式错误的 HTML 进行测试以确保。否则它可能会破坏您的 dom 和 xpath 查询。您也可以尝试使用 regexp 进行简单的字符串解析(不是 xml/html 解析,而是搜索某些字符串,例如 "
-
@LalMohan 看看我的回答。