0

我正在尝试使用 Ajax 从rss.news.yahoo.com/rss/topstories获取 RSS 提要文档,提取与“标题”标签关联的值并将它们回显到屏幕上。

xmlget.htm通过 GET 请求实现 Ajax。

xmlget.php使用 PHP 函数 file_get_contents 在 GET 变量 $_GET['url'] 中提供给它的 URL 处加载网页,并在屏幕上显示“标题”标签。

我得到的错误是这样的:

XML Parsing Error: junk after document element Location: moz-nullprincipal:{2f186a54-8730-4ead-9bf9-f82c8d56ad8f} Line Number 2, Column 1:

xmlget.htm

<html>
<head>
    <title>Ajax Example</title>
</head>
<body>
    <h1 style="text-align: center;">Loading a web page into a DIV</h1>
    <div id='info'>This sentence will be replaced</div>
<script>
    nocache = "&nocache="+Math.random()*1000000
    url = "rss.news.yahoo.com/rss/topstories"
    request = new ajaxRequest()
    request.open("GET","xmlget.php?url="+url+nocache,true)
    out = "";

    request.onreadystatechange = function(){
        if(this.readyState == 4){
            if(this.status == 200){
                if(this.responseXML != ""){
                    titles = this.responseXML.getElementsByTagName('title')
                    for (j = 0 ; j < titles.length ; ++j)
                        out += titles[j].childNodes[0].nodeValue + '<br />'
                    document.getElementById('info').innerHTML = out
                }
                else alert("Ajax error: No data received")
            }
            else alert( "Ajax error: " + this.statusText)
        }    
    }

    request.send(null)

    function ajaxRequest(){
        try{
            request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e1){
            try{
                request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e2){
                try{
                    request = new XMLHttpRequest()
                } catch (e3){
                    request = false
                }
            }
        }
        return request
    }
</script>
</body>

xmlget.php

<?php
if(isset($_GET['url'])){

    function SanitizeString($var) {
        $var = strip_tags($var);
        $var = htmlentities($var);
        return stripcslashes($var);
    }

    header('Content-Type: text/xml');
    echo file_get_contents("http://www.".SanitizeString($_GET['url']));

}

?>

4

2 回答 2

0

请在头部添加以下行

<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
于 2013-10-09T03:18:57.200 回答
0

发现问题了!file_get_contents函数无法找到主机,因为 url 无效。rofl... 不

正确

echo file_get_contents("http://www.".SanitizeString($_GET['url']));

正确的

echo file_get_contents("http://".SanitizeString($_GET['url']));
于 2013-10-09T07:25:27.970 回答