5

現在、リモート サイトの XML フィードを取得し、ローカル コピーをサーバーに保存して PHP で解析しています。

問題は、PHP でいくつかのチェックを追加して、feed.xml ファイルが有効かどうかを確認し、有効な場合は feed.xml を使用する方法です。

エラーで無効な場合 (リモート XML フィードで空白の feed.xml が表示される場合があります)、以前のグラブ/保存からの feed.xml のバックアップの有効なコピーを提供しますか?

コード取得 feed.xml

<?php
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,
'http://domain.com/feed.xml');
/**
* Create a new file
*/
$fp = fopen('feed.xml', 'w');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
/**
* Execute the cURL session
*/
curl_exec ($ch);
/**
* Close cURL session and file
*/
curl_close ($ch);
fclose($fp);
?>

これまでのところ、これをロードするだけです

$xml = @simplexml_load_file('feed.xml') or die("feed not loading");

ありがとう

4

3 に答える 3

4

curl がファイルに直接書き込む必要がない場合は、ローカルの feed.xml を書き直す前に XML を確認できます。

<?php
/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL, 'http://domain.com/feed.xml');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec ($ch);
curl_close ($ch);
if (@simplexml_load_string($xml)) {
    /**
    * Create a new file
    */
    $fp = fopen('feed.xml', 'w');
    fwrite($fp, $xml);
    fclose($fp);
}

?>
于 2010-02-14T18:27:07.947 に答える
3

これはどう?ドキュメントを取得するだけの場合は、curl を使用する必要はありません。

$feed = simplexml_load_file('http://domain.com/feed.xml');

if ($feed)
{
    // $feed is valid, save it
    $feed->asXML('feed.xml');
}
elseif (file_exists('feed.xml'))
{
    // $feed is not valid, grab the last backup
    $feed = simplexml_load_file('feed.xml');
}
else
{
    die('No available feed');
}
于 2010-02-14T19:11:47.263 に答える
0

私がまとめたクラスには、リモートファイルが存在するかどうか、およびリモートファイルがタイムリーに応答しているかどうかをチェックする関数があります。

/**
* Check to see if remote feed exists and responding in a timely manner
*/
private function remote_file_exists($url) {
  $ret = false;
  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_NOBODY, true); // check the connection; return no content
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1); // timeout after 1 second
  curl_setopt($ch, CURLOPT_TIMEOUT, 2); // The maximum number of seconds to allow cURL functions to execute.
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; da; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11');

  // do request
  $result = curl_exec($ch);

  // if request is successful
  if ($result === true) {
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($statusCode === 200) {
      $ret = true;
    }
  }
  curl_close($ch);

  return $ret;
}

フルクラスにはフォールバックコードが含まれており、常に何かを処理できるようになっています。

フルクラスを説明するブログ投稿はここにあります:http ://weedygarden.net/2012/04/simple-feed-caching-with-php/

コードはここにあります:https ://github.com/erunyon/FeedCache

于 2012-04-26T23:43:15.120 に答える