我想将数据从服务器推送到浏览器。我已经知道发送输出缓冲区的 php 函数 ob_flush()
。我需要一些逻辑方面的帮助。我正在使用 Facebook 实时 API,所以我想在每次 Facebook 访问我的网站时向用户推送数据。
这是我尝试将数据推送到浏览器但无法正常工作的代码。
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/event-stream');
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
error_log( "LOGS STARTS FROM HERE" );
if(isset($_GET['hub_challenge'])){
echo $_GET['hub_challenge'];
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
$updates = json_decode(file_get_contents("php://input"), true);
// Replace with your own code here to handle the update
// Note the request must complete within 15 seconds.
// Otherwise Facebook server will consider it a timeout and
// resend the push notification again.
print_r($updates);
ob_flush();
flush();
//file_put_contents('fb.log', print_r($updates,true), FILE_APPEND);
//error_log('updates = ' . print_r($updates, true));
}
?>
最佳答案
正如@som 所建议的,您可以简单地使用它们之间有间隔的请求,您不需要使用套接字。
但问题是,您正在尝试从 API 接收数据并将其直接传递给浏览器,所有这些都是一次性完成的。最好将这两个步骤分开。
在从 Facebook 接收数据的脚本中,将该数据存储在数据库或其他地方:
if($_SERVER['REQUEST_METHOD'] == "POST"){
$updates = json_decode(file_get_contents("php://input"), true);
insertDataToDatabase($updates); // you'll have to implement this.
}
然后设置一个监控页面:
monitor.php
<script>
lastId = 0;
$(document).ready(function() {
getNewDataAtInterval();
});
function getNewDataAtInterval() {
$.ajax({
dataType: "json",
url: "getData.php",
data: {lastId: lastId}
}).done(function(data) {
for(i=0; i<data.messages.length; i++) {
$("#messages").append("<p>" + data.messages[i]['id'] + ": " + data.messages[i]['message'] + "</p>");
if (data.messages[i]['id'] > lastId) lastId = data.messages[i]['id'];
}
setTimeout(getNewDataAtInterval, 10000);
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + jqXHR.responseText );
});
}
</script>
<div id="messages"></div>
最后,创建一个服务器端脚本来返回一个 JSON,其中包含从数据库加载的新消息。
getData.php
$lastId = $_GET['lastId'];
$newMessages = getUpdatesFromDatabase($lastId);
exit(json_encode(array("messages"=>$newMessages)));
function getUpdatesFromDatabase($lastId) {
// I'm using this array just as an example, so you can see it working.
$myData = array(
array("id"=>1,"message"=>"Hi"),
array("id"=>2,"message"=>"Hello"),
array("id"=>3,"message"=>"How are you?"),
array("id"=>4,"message"=>"I'm fine, thanks")
);
$newMessages = array();
foreach($myData as $item) {
if ($item["id"] > $lastId) {
$newMessages[] = $item;
$newLastId = $item["id"];
}
}
return $newMessages;
}
关于php - 将数据从服务器推送到用户浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102784/