Aka*_*mar 21 php json facebook push-notification
我想将数据从服务器推送到浏览器.我已经知道ob_flush()发送输出缓冲区的php函数了.我需要一些逻辑方面的帮助.我正在使用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));
}
?>
Run Code Online (Sandbox Code Playgroud)
正如@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.
}
Run Code Online (Sandbox Code Playgroud)
然后设置监控页面:
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>
Run Code Online (Sandbox Code Playgroud)
最后,创建一个服务器端脚本,以返回带有从数据库加载的新消息的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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6026 次 |
| 最近记录: |