我有以下文件,这就是他们所做的:
input.php:从 XML 提要中获取数据,连接到数据库并将其输入到数据库中。
output.php:连接到数据库并创建要输出的变量。
index.php:包含output.php
并使用变量来输出数据。
refresh.js: Ajax 刷新 div 以更新数据。
输入.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' );
输出.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>
刷新.js
var auto_refresh = setInterval(
function() {
$('#read').load('index.php #read');
}, 2000);
问题是除非我刷新input.php
(这会破坏增量计数),否则数据不会插入数据库。我不知道为什么会这样。有什么想法吗?
注意:因为我刚刚开始学习更多关于 PHP 和数据库的知识,所以我希望我的代码input.php
和output.php
代码在需要时进行最小限度的更改。