【问题标题】:Alternative for DOMDocument()DOMDocument() 的替代方案
【发布时间】:2014-02-28 00:57:59
【问题描述】:

我正在使用 DOMDocument() 在我的代码中包含 RSS 提要。但是我得到这个错误:

在服务器配置中禁用 URL 文件访问

那是因为我的服务器不允许我修改 php.ini 文件或将 allow_url_fopen 设置为 ON。

有解决办法吗?这是我的完整代码:

<?php
$rss = new DOMDocument();
$rss->load('rss.php');

$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 5;
echo '<table>';
for($x=0;$x<$limit;$x++) {
 $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
 $link = $feed[$x]['link'];

 echo <<<EOF
 <tr>
  <td><a href="$link"><b>$title</b></a></td>
 </tr>
EOF;
}
echo '</table>';
?>

谢谢。

【问题讨论】:

  • 除非 allow_url_fopen 设置为 ON ,否则您将无法访问远程 URL。
  • 它实际上有点奇怪,因为 RSS 提要在我的同一台服务器上......
  • 使用 DOM 加载本地文件不需要 URL 文件访问。一定有其他问题。但就像随机拍摄一样尝试 $dom->loadXml(file_get_content('rss.php'))。另请注意,当您在本地加载 rss.php 时,不会执行该 rss.php 中的 PHP,因此无论如何这可能都不是您想要的。
  • 谢谢,但没用。它说 Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '

标签: php ini


【解决方案1】:

好的,我自己解决了。

<?php

$k = 'rss.php';
$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $k);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $rss = curl_exec($ch);
    curl_close($ch);

    $xml = simplexml_load_string($rss, 'SimpleXMLElement', LIBXML_NOCDATA);

    $feed = array();
    foreach($xml->channel->item as $item){
     $item = array (
     'title' => $item->title,
     'desc' => $item->description,
     'link' => $item->link,
     'date' => $item->pubDate,
     );
     array_push($feed, $item);
    }
$limit = 5;
echo '<table>';
for($x=0;$x<$limit;$x++) {
 $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
 $link = $feed[$x]['link'];
 echo <<<EOF
 <tr>
  <td><a href="$link"><b>$title</b></a></td>
 </tr>
EOF;
}
echo '</table>';
?>

【讨论】:

    【解决方案2】:

    使用 cURL 命令。您确实应该将其用于服务器到服务器的交互,而不是尝试将 URL 传递给构造函数。

    这是 cURL 文档 - http://us1.php.net/curl

    我还有一个简单的基于 cURL 的 REST 客户端,您可以随意使用 - https://github.com/mikecbrant/php-rest-client

    基本上,您要做的就是使用 cURL 来检索远程内容,而不是尝试使用 fopen 包装器直接打开它。检索内容后,将其传递给 DOMDocument。

    【讨论】:

    • 我添加了我的完整代码。请检查一下。我不知道如何将其转换为 curl。
    • @CainNuke 您只需调用 $rss->load($content) 其中 $content 包含通过 cURL 检索到的 rss.php 的内容。您的其余代码不需要更改。阅读 cURL 文档,或在 SO 上查找有关 cURL 的其他帖子。我不会为你写完整的东西。
    • 我在 OP 的代码中没有看到任何 URL,所以应该没有必要使用 cURL。
    • @Jack 是的,他很可能只能从本地文件中读取内容。给出原始答案时尚未提供实际代码。
    • 当我这样做时,我收到以下错误:警告:DOMDocument::load() [domdocument.load]: Start tag expected, '
    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 2015-03-03
    • 2015-09-25
    • 2019-12-16
    • 2011-06-20
    • 2015-11-03
    • 2014-04-03
    • 2011-12-13
    相关资源
    最近更新 更多