PHP代理获取跨域xml并使用jQuery进行解析

时间:2017-01-18 00:46:01

标签: php jquery xml

由于Google的Feed加载服务已关闭,我很难找到一种新方法来显示跨不同协议和域的xml Feed。我需要在博客中加入网站。该网站是https,博客不是。我在这里取得了一些成功,但仅限于获得冠军。我需要在链接中包含标题,然后将其插入到li中。让它工作,需要将其放入DOM中

这是我的代理路径是(/SSI/Processor/feedProxy.php):

<?php
    function download_page($path){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$path);
    curl_setopt($ch, CURLOPT_FAILONERROR,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $retValue = curl_exec($ch);          
    curl_close($ch);
    return $retValue;
}

$sXML = download_page('https://www.external.com/feeds/feed.xml');
$oXML = new SimpleXMLElement($sXML);

$items = $oXML->entry;
$i = 0;
foreach($items as $item) {
    $title = $item->title;
    $link = $item->link;
    echo '<li>';
    foreach($link as $links) {
    $loc = $links['href'];
    echo "<a href=\"$loc\">";
}
echo $title;
echo "</a>";;
echo "</li>";
if(++$i == 3) break;
}
?>

修改

我现在可以获取所有返回的xml,并通过PHP格式化。我只是不能用jQuery将它插入DOM!

我的jQuery:

$(function(){
    $.ajax({
    type: "GET",
    url:'/SSI/Processor/feedProxy.php',
    dataType: "html",
    success: function(html) {
        console.log(html);
        //console log is showing the formatted HTML
        $('#feeds').html(html);
    });
});

我正在努力解决如何在PHP中解析它。它需要输出如下:<li><a href="linkfromxml">link text</a></li>并将其附加到div。

1 个答案:

答案 0 :(得分:1)

您要返回html,但是您要将dataType设置为xml

将其更改为dataType:'html'