php实现wopi
PHP 实现 WOPI 的步骤
WOPI (Web Application Open Platform Interface) 是微软 Office Online 和 Office for the Web 的开放平台接口,允许第三方应用集成 Office 的在线编辑功能。以下是使用 PHP 实现 WOPI 的基本方法。
配置 WOPI 发现端点
WOPI 客户端(如 Office Online)通过发现端点获取服务器的能力信息。需要在服务器上提供一个 XML 文件,描述支持的 WOPI 操作。
<wopi-discovery>
<net-zone name="internal-http">
<app name="Excel" favIconUrl="http://yourdomain.com/favicon.ico">
<action name="view" ext="xlsx" urlsrc="http://yourdomain.com/wopi/files/<id>/contents"/>
<action name="edit" ext="xlsx" urlsrc="http://yourdomain.com/wopi/files/<id>/contents"/>
</app>
</net-zone>
</wopi-discovery>
实现 WOPI 端点
WOPI 客户端会通过 REST API 与服务器交互。需要在 PHP 中实现以下关键端点:
-
CheckFileInfo: 返回文件的基本信息。

// GET /wopi/files/<file_id> header('Content-Type: application/json'); echo json_encode([ 'BaseFileName' => 'example.xlsx', 'OwnerId' => 'user1', 'Size' => filesize($file_path), 'UserId' => 'user1', 'Version' => filemtime($file_path) ]); -
GetFile: 返回文件内容。
// GET /wopi/files/<file_id>/contents header('Content-Type: application/octet-stream'); readfile($file_path); -
PutFile: 保存文件修改。

// POST /wopi/files/<file_id>/contents $file_content = file_get_contents('php://input'); file_put_contents($file_path, $file_content);
实现锁定机制
WOPI 要求实现文件锁定机制,防止并发编辑冲突。
// POST /wopi/files/<file_id>
$data = json_decode(file_get_contents('php://input'), true);
if ($data['Lock']['LockId'] !== $current_lock_id) {
http_response_code(409);
echo json_encode(['Lock' => $current_lock_id]);
exit;
}
验证请求
所有 WOPI 请求都包含访问令牌,需要在服务器端验证。
$access_token = $_GET['access_token'];
if (!validate_token($access_token)) {
http_response_code(401);
exit;
}
集成 Office Online
在网页中嵌入 Office Online 的 iframe。
<iframe
src="https://your-office-online-server/we/wordeditorframe.aspx?
WOPISrc=http://yourdomain.com/wopi/files/123">
</iframe>
注意事项
- 确保服务器支持 HTTPS,WOPI 要求所有通信加密。
- 实现完整的权限控制和用户验证。
- 处理所有必需的 WOPI 操作和错误响应。
- 定期测试与 Office Online 的兼容性。
以上是 PHP 实现 WOPI 的基本框架,实际部署时需要根据具体需求调整和完善。






