Grab, Cache 및 Parse Remote XML 피드, PHP의 유효성 검사 검사
-
20-09-2019 - |
문제
현재 원격 사이트의 XML 피드를 잡고 PHP에서 구문 분석 할 서버에 로컬 사본을 저장하고 있습니다.
문제는 PHP에 약간의 검사를 추가하여 Feed.xml 파일이 유효한지 확인하고 Feed.xml을 사용하는 방법입니다.
그리고 오류가 유효하지 않은 경우 (때로는 원격 XML 피드 Somes가 빈 피드를 표시) 이전 GRAP/SAVE에서 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');
/**
* 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");
감사해요
해결책
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);
}
?>
다른 팁
이건 어때? 문서를 검색 해야하는 경우 컬을 사용할 필요가 없습니다.
$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');
}
내가 합한 클래스에는 원격 파일이 존재하는지 확인하고 적시에 응답하는지 확인하는 기능이 있습니다.
/**
* 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
제휴하지 않습니다 StackOverflow