Pergunta

Atualmente, estou pegando o feed XML de um site remoto e salvando uma cópia local no meu servidor para ser analisada no PHP.

O problema é como adicionar algumas verificações no PHP para ver se o arquivo feed.xml é válido e, se assim for, use feed.xml.

E se inválido com erros (dos quais às vezes o feed XML remoto, um pouco exibir feed.xml em branco), sirva uma cópia válida de backup do feed.xml de Grab/salvamento anterior?

Código de captura de 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);
?>

Até agora só tem isso para carregá -lo

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

obrigado

Foi útil?

Solução

Se não for pricipial que o Curl seja gravado diretamente no arquivo, você pode verificar o XML antes de reescrever o feed.xml local:

<?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);
}

?>

Outras dicas

Que tal agora? Não há necessidade de usar o CURL se você precisar recuperar um documento.

$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');
}

Em uma aula que montei, tenho uma função que verifica se o arquivo remoto existe e se está respondendo em tempo hábil:

/**
* 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;
}

A classe completa contém código de devolução para garantir que sempre tenhamos algo para trabalhar.

A postagem do blog explicando a aula completa está aqui: http://weedygarden.net/2012/04/simple-feed-caching-with-php/

O código está aqui: https://github.com/erunyon/feedcache

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top