次のファイルがあり、これがその機能です。
input.php: XML フィードからデータを取得し、データベースに接続して入力します。
output.php:データベースに接続し、出力する変数を作成します。
index.php:変数を含めoutput.php
て使用し、データを出力します。
refresh.js: div を更新してデータを更新するための Ajax。
入力.php
$xml = simplexml_load_file( "http://domain.com/feed" );
$json = json_encode( $xml );
$array = json_decode( $json,TRUE );
$items = $array['channel']['item'];
$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
print "failed to connect to DB: {$DB->connect_error}";
exit( 1 );
}
$match = "#^(?:[^\?]*\?url=)(https?://)(?:m(?:obile)?\.)?(.*)$#ui";
$replace = '$1$2';
foreach( $items as $item ){
$title = $item['title'];
$url = preg_replace( $match,$replace,$item['link'] );
$title_url[] = array( $title,$url );
$sql_values[] = "('{$DB->real_escape_string( $title )}','{$DB->real_escape_string( $url )}')";
}
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES\n ".implode( "\n,",array_reverse( $sql_values ) );
if( $DB->query( $SQL ) ){
} else {
print "failed to INSERT: [{$DB->errno}] {$DB->error}";
}
$DB->set_charset( 'utf8' );
Output.php
$DB = new mysqli( 'localhost','USERNAME','PASSWORD','DATABASE' );
if( $DB->connect_errno ){
print "failed to connect to DB: {$DB->connect_error}";
exit( 1 );
}
$query = "SELECT `title`,`url` FROM `read` ORDER BY `order` DESC";
$result = $DB->query( $query );
// error-handling: make sure query returned a result
if( $result ){
while( $row = $result->fetch_array() ){
// list gets values from a numeric array
list( $title,$url ) = $row;
// using [] (append) is much faster than using array_push()
$data[] = array( 'title'=>$title,'url'=>$url );
}
$title = $data[0]['title'];
$url = $data[0]['url'];
}else{
//do something
}
インデックス.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Recently</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/refresh.js"></script>
</head>
<body>
<?php include_once "includes/output.php"; ?>
<p class="title"><span>Read </span>
<a id="read" href="<?php echo $url; ?>" target="_blank"><?php echo $title; ?></a>
</p>
</body>
</html>
Refresh.js
var auto_refresh = setInterval(
function() {
$('#read').load('index.php #read');
}, 2000);
input.php
問題は、 (インクリメント カウントを台無しにする) 更新しない限り、データがデータベースに挿入されないことです。なぜこれが起こっているのか分かりません。何かご意見は?
注:私は PHP とデータベースについて学び始めたばかりなので、必要に応じてコードinput.php
とoutput.php
コードを最小限に変更することをお勧めします。