【发布时间】:2011-06-25 06:49:25
【问题描述】:
我有一个 PHP 页面,它将从 downloads.nl 收集 mp3 链接。结果将转换为 XML 并呈现良好。
当我尝试使用 ajax 读取该 XML 时,就会出现问题。这些文件在同一个域上,这真的让我很困惑。这是我的 php 爬虫。
<?php
header("Content-type: text/xml");
$artistname = $_GET['artistname'];
$trackname = $_GET['trackname'];
$newartistname = str_replace(" ","+",$artistname);
$newtrackname = str_replace(" ","+",$trackname);
$target_url = "http://www.downloads.nl/results/mp3/1/".$newartistname."+".$newtrackname;
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
error_reporting(0);
// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
if (!$html) {
echo "<br />cURL error number:" .curl_errno($ch);
echo "<br />cURL error:" . curl_error($ch);
exit;
}
// parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);
// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
echo '<?xml version="1.0"?>';
echo '<downloads>';
echo '<trackname>'.$newartistname."+".$newtrackname.'</trackname>';
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
if(strpos($url, ".cgi")){
echo '<link>http://downloads.nl'.htmlspecialchars($url,ENT_QUOTES).'</link>';
}
}
echo '</downloads>';
?>
这是我的 javascript 函数
function getDownloadLink(artistname,trackname){
var xmlhttp4;
if (window.XMLHttpRequest){
xmlhttp4 = new XMLHttpRequest();
}
else{
xmlhttp4 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp4.onreadystatechange=function(){
alert(xmlhttp4.readyState);
if (xmlhttp4.readyState==4 && xmlhttp4.status==200){
try{
var downloadlink = xmlhttp4.responseXML.documentElement.getElementsByTagName("downloads");
for (var i=0;i<downloadlink.length;i++){
alert(i);
}
}
catch(er){
alert(xmlhttp4.responseText);
}
}
else{
alert("ReadyState: "+xmlhttp4.readyState+" Status: "+xmlhttp4.status);
}
}
xmlhttp4.open("GET","http://localhost/bone/searchmusic.php?artistname="+artistname+"&trackname="+trackname,true);
xmlhttp4.send(null);
}
我不知道问题是什么。是我没有正确呈现 XML 还是缺少我的 ajax?
谢谢,
山姆
【问题讨论】:
-
感谢史蒂夫。我选择了解决我问题的答案。我不知道这个功能。
-
你没有在任何地方提到问题是什么
-
感谢您的评论安迪。我会试试的
-
PHP爬虫工作正常吗?如果是这样,我有 AJAX 部分的解决方案。我只是无法让 PHP 工作,
curl目前不适合我。
标签: php javascript xml ajax web-crawler