为什么新的SimpleXMLElement会导致500错误?

时间:2019-01-25 20:22:20

标签: php xml wordpress

我有一个简单的脚本,到昨天为止已经运行了2年。我只是从WP网站获取XML提要,并将其格式化以显示在其他网站上。这是代码:

<?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://example.com/tradeblog/feed/atom/');
$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'];
        $href = str_replace("/feed/atom/", "", $loc);
        echo "<a href=\"$href\" target=\"_blank\">";
    }
    echo $title;
    echo "</a>";;
    echo "</li>";
    if(++$i == 3) break;
}

?>

我可以回显$ sXML,它将按预期显示整个XML内容。当我尝试回显$ oXML时,出现500错误。 $ oXML的任何使用都会导致500。发生了什么变化?是否有其他/更好的方法来使用PHP?

2 个答案:

答案 0 :(得分:1)

似乎您的xml源不完全是xml。我尝试使用w3 scholl validator对其进行验证,并引发错误。也尝试过here,并得到了相同的错误。

答案 1 :(得分:1)

不知道为什么,但是这可行

<?php
    $rss = new DOMDocument();
    $rss->load('https://example.com/tradeblog/feed/rss2/');

    $feed = array();
    foreach ($rss->getElementsByTagName('item') as $node) {
    $item = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
    );
    array_push($feed, $item);
}

$limit = 3;
for($x=0;$x<$limit;$x++) {
    $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
    $link = $feed[$x]['link'];

    echo '<li><a href="'.$link.'" title="'.$title.'">'.$title.'</a></li>';
}

?>
相关问题