Mac下安装php的mongodb扩展

来源:互联网 发布:易奇八字准不准知乎 编辑:程序博客网 时间:2024/06/05 20:46

背景:

使用mac中已经自带的php,而默认情况下是没有mongodb扩展的,所以还无法使用php脚本访问mongodb


已经安装了brew,这个是mac下非常好用的一个安装软件的工具,类似于ubuntu下的apt-get,rpm等,直接使用brew search 或brew install就可以安装所需的工具。

通过brew search mongo,查到下列相关软件:

homebrew/php/php53-mongo         homebrew/php/php56-mongo✔       mongo-c-driver                   mongodb@3.0

homebrew/php/php54-mongo         homebrew/php/php56-mongodb       mongo-cxx-driver                 mongodb@3.2

homebrew/php/php54-mongodb       homebrew/php/php70-mongodb       mongo-orchestration              mongoose

homebrew/php/php55-mongo         homebrew/php/php71-mongodb       mongodb ✔                        percona-server-mongodb

homebrew/php/php55-mongodb       homebrew/php/php72-mongodb       mongodb@2.6


通过php -v,可以看到当前的php版本

php -v

PHP 5.6.30 (cli) (built: Mar 11 2017 09:56:27) 

Copyright (c) 1997-2016 The PHP Group

Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies


所以,选择了安装php56-mongo。执行命令 brew install homebrew/php/php56-mongo

然而,事情并没有想象得那么简单。。 安装后还是无法使用mongo扩展,搜索后,发现这篇文章:http://www.cnblogs.com/gabrialrx/p/5509018.html

内容很简单,但也很有效,内容如下:

brew install php56-mongo之后,启动php报这个错误

Warning: PHP Startup: mongo: Unable to initialize module

解决办法是source安装mongo扩展。

brew reinstall php56-mongo --build-from-source

果然,执行上述操作后,通过 php -m命令即可查询已安装的扩展。

php -m|grep mongo

mongo


最后通过下面的php脚本即可验证(先确认mongodb已安装并且启动)。

<?php$m = new MongoClient(); // 连接默认主机和端口为:mongodb://localhost:27017$db = $m->test; // 获取名称为 "test" 的数据库$collection = $db->tcol; // 选择集合$cursor = $collection->find();// 迭代显示文档标题foreach ($cursor as $document) {    echo $document["id"].'  '.$document["name"] . "\n";}


原创粉丝点击