事实/事实PHP驱动程序

此软件包已被废弃,不再维护。没有建议的替代软件包。

这是Factual公共API的官方PHP驱动程序。

安装次数: 66,257

依赖关系: 0

建议者: 0

安全: 0

星标: 47

关注者: 38

分支: 28

开放问题: 9

类型:php驱动程序

dev-master 2016-04-11 15:43 UTC

This package is not auto-updated.

Last update: 2017-07-14 06:31:40 UTC


README

#介绍 这是Factual API的官方PHP驱动程序的介绍。它由纯手工制作的原木精制而成。

此驱动程序允许您创建一个认证的Factual句柄。有了Factual句柄,您可以通过PHP数组和对象发送查询并获取结果。

许多Bothamns为了提供此文档而献身。

#PHP特定性 ##依赖项

  • 需要PHP >=5.1.2。
  • 需要php5-curl模块。
  • 需要SPL进行自动加载。
  • 需要JSON。从PHP 5.5rc2开始,一些发行版缺少之前包含的JSON扩展,因为存在许可冲突。使用sudo apt-get install php5-json。

该软件包包含轻微修改后的Google的oauth库

##自动加载所有类都自动加载。只需require_once("Factual.php")即可。

PHP __autoload()方法已弃用;此库使用spl_autoload_register()。Factual自动加载不会干扰其他库或框架。

#入门

获取OAuth密钥和密码

从Factual获取OAuth密钥和密码,网址为https://www.factual.com/api-keys/request。不要将您的密码泄露给第三方或将其分布在PHP代码中(提醒:这就是为什么它被称为'密码')。

测试您的集成和环境

命令行上运行test.php

'php test.php yourFactualKey yourFactualSecret [logfile]'

在Windows上,请记得使用-f开关

'php -f test.php yourFactualKey yourFactualSecret [logfile]'  

这将检查您的PHP安装环境和执行多项单元测试。该脚本将您的密钥作为第一个参数,您的密码是第二个参数,可选的输出文件是第三个参数。默认情况下,它将输出到stdout。

使用驱动程序

需要文件'Factual.php',并使用密钥和密码作为参数实例化Factual对象

    //setup
    require_once('Factual.php');
    $factual = new Factual("yourOauthKey","yourOauthSecret");

驱动程序在实例化时创建一个认证的Factual句柄并配置类加载,因此请确保始终首先实例化一个Factual对象。

简单查询示例

(记住,首先创建一个Factual对象,如我们上面所做的那样。)

    // Find 3 random records 
    $query = new FactualQuery;
    $query->limit(3);
    $res = $factual->fetch("places", $query);
	print_r($res->getData());

全文搜索示例

    // Find entities that match a full text search for Sushi in Santa Monica:
    $query = new FactualQuery;
	$query->search("Sushi Santa Monica");
    $res = $factual->fetch("places", $query);
	print_r($res->getData());

有关迭代查询结果和获取查询元数据的详细信息,请参阅处理查询结果

不必要的提醒:我们在这几个示例中使用print_r()以便您可以从视觉上审查输出。显然,但仍然值得提醒,您不希望在生产中使用print_r()。

驱动程序中提供了大量工具,可以帮助您了解您的请求以及服务器返回的内容(或未返回的内容)

#调试和支持

获取帮助的地方

如果您有任何问题或遇到任何其他问题,例如Factual API的意外数据或异常行为(或者您不确定发生了什么),请通过Factual支持联系我们。请确保包括调试信息以及您正在使用的驱动程序;帮助我们帮助您。提供尽可能多的信息,包括

  • 异常输出的所有调试信息(上面)
  • 您为了暴露错误所做的事情——请提供带有值的特定代码,而不是变量
  • 您期望发生的事情以及实际上发生的事情
  • 详细的堆栈跟踪和/或行号

##调试模式可以将Factual对象切换到调试模式,该模式将回显(到stderr)cURL进程和我们可以提供的任何其他信息

	$factual = new Factual($key,$secret);
	$factual->debug();

当启用调试模式时,cURL状态和异常也将输出到stderr

###cURL调试输出 * 即将连接到api.v3.factual.com端口80 (#0) * 尝试连接到107.20.247.254... * 已连接 * 连接到api.v3.factual.com (107.20.247.254) 端口80 (#0) > POST /t/2EH4Pz/f33527e0-a8b4-4808-a820-2686f18cb00c/submit HTTP/1.1 User-Agent: anyMeta/OAuth 1.0 - ($LastChangedRevision: 174 $) Host: api.v3.factual.com Accept: / X-Factual-Lib: factual-php-driver-v1.4.3 Content-Type: application/x-www-form-urlencoded Authorization: OAuth realm="", oauth_signature_method="HMAC-SHA1",
oauth_signature="fjnDOdqNS8vYHxmalIy%2BS9dC2%2Bw%3D", oauth_nonce="500c7f9dd13fc",
oauth_timestamp="1342996381", oauth_token="", oauth_consumer_key="9AlBWqvNukzwsv8qu4RTPztAKcTLYohAMxHmxtQl",
oauth_version="1.0" Content-Length: 102

< HTTP/1.1 400 Bad Request
< access-control-allow-origin: *
< age: 0
< cache-control: max-age=2592000
< Content-Type: application/json; charset=utf-8
< Date: Sun, 22 Jul 2012 22:33:02 GMT
< Server: nginx/1.0.15
< Content-Length: 196
< Connection: keep-alive
< 
* Connection #0 to host api.v3.factual.com left intact
* Closing connection #0

###异常调试输出 Array ( [code] => 400 [version] => 3 [status] => error [error_type] => InvalidJsonArgument [message] => 参数 'values' 在其JSON语法中包含错误。
有关文档,请参阅:http://developer.factual.com。 [request] => http://api.v3.factual.com/t/2EH4Pz/f33527e0-a8b4-4808-a820-2686f18cb00c/submit [returnheaders] => Array ( [access-control-allow-origin] => * [age] => 0 [cache-control] => max-age=2592000 [content-type] => application/json; charset=utf-8 [date] => Sun, 22 Jul 2012 22:33:02 GMT [server] => nginx/1.0.15 [content-length] => 196 [connection] => keep-alive )

[driver] => factual-php-driver-v1.4.3
[method] => POST
[body] => Array
    (
        [user] => testUser
        [values] => %7B%22factual_id%22%3A%22f33527e0-a8b4-4808-a820-2686f18cb00c%22%7D
    )

)

##异常处理如果Factual的API指示错误,将抛出一个未检查的FactualApiException异常。可以通过(上面)的调试模式或调用FactualApiException::debug()来研究详细的调试信息。以下是一个捕获FactualApiException并检查它的示例

    try{
    	$query->field("badFieldName")->notIn("Los Angeles"); //this line borks 
    	$res = $factual->fetch("places", $query);
    } catch (FactualApiException $e) {
      	print_r($e->debug());
    }

##调用内省许多Result对象方法允许内省调用本身。这些可以在任何时候访问,而无需将Factual对象设置为调试模式

方法 函数 说明
getCode() 获取Factual返回的HTTP状态码 对于从弃用中重定向很有用
getHeaders() 获取Factual返回的HTTP头
getTable() 获取查询的表名
getRawRequest() 获取url-encoded请求字符串 不包括认证组件
getRequest() 获取url-decoded请求字符串 (如上所述)
isEmpty() 检查Factual是否返回了数据
size() 获取本页结果集中返回的元素计数(不是总计数)
getVersion() 获取Factual API版本
getStatus() 获取Factual API服务器返回的状态 例如:“OK”
getJSON() 获取Factual返回的整个JSON字符串

#模式模式端点返回表元数据

	$res = $factual->schema("places");
	print_r($res->getColumnSchemas());

模式API文档:http://developer.factual.com/api-docs/#Schema

读取

使用读取API调用,通过全文搜索、参数过滤和地理位置过滤的任意组合查询Factual表中的数据。

读取API文档: http://developer.factual.com/api-docs/#Read

相关特定地点文档

##读取过滤器 使用以下语法对Factual数据进行搜索

参数 描述 示例
filters 限制返回的数据符合特定条件。
For all possible Row Filters, see the eponymous section, below.

</td>
<td><tt>$query->field("name")->beginsWith("Starbucks")</tt></td>
include count 包含符合请求的行数总和。请求行数将增加返回响应所需的时间。默认行为是不包含行数。当请求行数时,响应对象将通过 .getTotalRowCount() 包含有效的总行数。 $query->includeRowCount()
geo 限制返回的数据位于基于地理位置的范围内。 (见地理位置过滤器部分)
limit 返回的最大行数。默认为20。系统最大值为50。如需更高限制,请联系Factual,但请考虑如果您的用例需要在一个查询中请求比满足单个最终用户请求所需更多的数据,则请请求下载数据。 $query->limit(10)
search 全文搜索查询字符串。 查找 "sushi"
$query->search("sushi")

查找 "sushi" 或 "sashimi"
$query->search("sushi, sashimi")

查找 "sushi" 和 "santa" 和 "monica"
$query->search("sushi santa monica")

offset 在返回数据页之前跳过的行数。最大值为500减去任何在limit下提供的值。默认为0。 $query->offset(150)
select 在查询结果中包含哪些字段。请注意,由于JSON散列的性质,字段顺序可能不会在结果JSON响应中得到保留。 $query->only("name,tel,category") 或 $query->select(array("name","tel","category"))
sort 要排序数据字段(或字段),以及排序方向。如果指定了地理位置过滤器,则支持 $distance 作为排序选项。如果指定了全文搜索(使用q参数或使用过滤器参数中的 $search 操作符),则支持 $relevance 作为排序选项。默认情况下,任何使用全文搜索的查询将按相关性排序。任何具有地理位置过滤器的查询将按参考点距离排序。如果同时存在地理位置过滤器和全文搜索,则默认为相关性后跟距离。 $query->sortAsc("name")
threshold 设置对Factual认为地点存在的置信度级别的阈值。有效值是 confident、default 或 comprehensive。如果没有指定阈值参数,则使用 default 值。 $query->threshold("confident");

##从查询结果中提取数据 驱动程序为您解析JSON,并作为 factual::fetch() 的结果返回一个 result 对象,但您可以直接与JSON、数组或对象一起工作。在这些示例中,$res 是 API 查询返回的 result 对象

	//Get the original JSON (includes status and metadata)
	$res = $res->getJson();
	
	//Get the entities as array of arrays
	$res = $res->getData();
	
	//Get the entities as a JSON array
	$res = $res->getDataAsJSON();	

	//iterate through the result records, just like an array
	foreach ($res as $entity){
	//your code
	}

为了帮助调试,我们还在响应对象中提供了有关查询和响应的元数据。请参阅上面的调用内省部分。

##字段选择 默认情况下,您的查询将返回表中的所有字段。您可以使用 only 修饰符来指定返回的确切字段集。例如

    // Build a Query that only gets the name, tel, and category fields:
	$query = new FactualQuery;
	$query->limit(10);    
    $query->only("name,tel,category");
	$res = $factual->fetch("places", $query);
	print_r($res->getData());  

##行过滤器 驱动程序支持各种行过滤器逻辑。请参阅行过滤器API文档

示例

    // Build a query to find places whose name field starts with "Starbucks"
    $query = new FactualQuery;
    $query->field("name")->beginsWith("Starbucks");
    $res = $factual->fetch("places", $query);
	print_r($res->getData());  

    // Build a query to find places with a blank telephone number
    $query = new FactualQuery;
    $query->field("tel")->blank();
    $res = $factual->fetch("places", $query);
	print_r($res->getData());

支持的行过滤逻辑

谓词 描述 示例
等于 等于 $query->field("region")->equal("CA")
不等于 不等于 $query->field("region")->notEqual("CA")
search 全文搜索 $query->field("name")->search("fried chicken")
等于任何一个。需要数组。 $query->field("region")->in(array("MA", "VT", "NH", "RI", "CT"))
不在 不等于任何一个。需要数组。 $query->field("locality")->notIn(array("Los Angeles","Philadelphia"))
以...开头 以...开头 $query->field("name")->beginsWith("b")
不以...开头 不以...开头 $query->field("name")->notBeginsWith("star")
以任何一个开头 以任何一个开头。需要数组。 $query->field("name")->beginsWithAny(array("star", "coffee", "tull"))
不以任何一个开头 不以任何一个开头。需要数组。 $query->field("name")->notBeginsWithAny(array("star", "coffee", "tull"))
空白 为空或为null $query->field("tel")->blank()
非空白 不为空或不为null $query->field("tel")->notBlank()
大于 大于 $query->field("rating")->greaterThan(7.5)
大于等于 大于等于 $query->field("rating")->greaterThanOrEqual(7.5)
小于 小于 $query->field("rating")->lessThan(7.5)
小于等于 小于等于 $query->field("rating")->lessThanOrEqual(7.5)
包含 包含此值 $query->field("category_ids")->includes(10)
包含任何一个 包含这些值中的任何一个。需要数组。 $query->field("cuisine")->includesAny(array("sushi","bistro"))

AND

查询支持逻辑AND行过滤。例如

    // Build a query to find entities where the name begins with "Coffee" AND the telephone is blank:
    $query = new FactualQuery;
    $query->_and(
    	array(
       		$query->field("name")->beginsWith("Coffee"),
  	   		$query->field("tel")->blank()
  	   	)
	);
	$res = $factual->fetch("places", $query);
	print_r($res->getData());

注意,查询顶层设置的行过滤都隐式AND在一起,因此您也可以这样做

    //Combined query alternative syntax
    $query = new FactualQuery;
    $query->field("name")->beginsWith("Coffee");
    $query->field("tel")->blank();
    $res = $factual->fetch("places", $query);
	print_r($res->getData());

OR

查询支持逻辑OR行过滤。例如

    // Build a query to find entities where the name begins with "Coffee" OR the telephone is blank:
    $query = new FactualQuery;
    $query->_or(array(
       	$query->field("name")->beginsWith("Coffee"),
  	   	$query->field("tel")->blank()
  	   )
	);	
	$res = $factual->fetch("places", $query);
	print_r($res->getData());

组合AND和OR

您可以嵌套AND和OR逻辑到所需的任何复杂度。例如

    // Build a query to find entities where:
    // (name begins with "Starbucks") OR (name begins with "Coffee")
    // OR
    // (name full text search matches on "tea" AND tel is not blank)
    $query = new FactualQuery;    
    $query->_or(array(
        $query->_or(array(
            $query->field("name")->beginsWith("Starbucks"),
            $query->field("name")->beginsWith("Coffee")
            )
        ),
        $query->_and(array(
            $query->field("name")->search("tea"),
            $query->field("tel")->notBlank()
        	)
        )
      )
    );
	$res = $factual->fetch("places", $query);
	print_r($res->getData());

##地理过滤地理过滤提供了查询Factual中位于圆形、矩形或靠近点的实体的方式

圆形(点/半径)

	// Find entities located within 5000 meters of a latitude, longitude
	$query->within(new FactualCircle(34.06018, -118.41835, 5000)); //lat, lon, radius
  • 当使用点/半径地理过滤时,距离(以米为单位)将在响应包中的$distance键下返回。这个距离是按照直线距离计算的。
  • 点/半径查询实现为一个正方形的中心点,边长是半径的两倍。
  • 点/半径查询的半径限制为15公里。

	// Find entities located adjacent to a latitude, longitude
	$query->at(new FactualPoint(34.06018, -118.41835));
  • 点查询只是圆形查询的快捷方式,隐含的半径为500米。

矩形

	// Find entities located within a box over LA
	$query->within(new FactualRectangle(34.06110,-118.42283,34.05771,-118.41399)); 
  • 点的顺序是[top,left],[bottom,right]
  • 点始终按[latitude, longitude]顺序排列。

关于地理过滤的说明

  • 距离始终以米为单位指定
  • 任何地理查询可以包含的最大面积是900平方公里
  • 按距离排序需要特殊$distance运算符。务必转义美元符号
	$query->sortAsc("\$distance"); //order results 

##通过Factual ID搜索(FetchRow)fetchrow()方法通过Factual ID检索实体。这是一个简单的快捷方式,相当于在Factual ID上设置过滤,并返回一个只有一个元素的数组,就像常规读取一样

	//get started
	require_once('Factual.php');
	$factual = new Factual($key,$secret);
	//assign vars
	$factualID = "03c26917-5d66-4de9-96bc-b13066173c65";
	$tableName = "places";
	//fetch row
	$res = $factual->fetchRow($tableName, $factualID);
	print_r($res->getData());

##结果分页:限制和偏移量 您可以使用限制和偏移量来支持基本的结果分页。例如

    // Build a Query with offset of 150, limiting the page size to 10:
    $query = new FactualQuery;
	$query->limit(10);
	$query->offset(150);
	$res = $factual->fetch("places", $query);
	print_r($res->getData());

注意:驱动程序旨在运行时访问Factual的API。我们对任何唯一组合的过滤器强制执行500行的深度分页限制:http://developer.factual.com/data-docs/

这是一种礼貌的说法,我们希望您不要使用我们的API来抓取Factual数据进行永久保留。我们确实提供整个数据集的下载:请联系 partnership@factual.com

##总行数 默认情况下,Factual不会返回匹配您过滤器的记录总数——计算这个值有适度的开销。但我们确实提供了显式检索它的选项。

要获取符合您查询条件的所有实体的总数,请使用FactualQuery::includeRowCount()方法在查询对象中设置参数

	$query = new FactualQuery;
	$query->field("postcode")->equal("95008");
	$query->includeRowCount();

使用Factual::fetch()执行查询后,可以通过在响应对象上调用ReadResponse::getTotalRowCount()来获取结果数

	$res = $factual->fetch("places", $query); 
	print_r($res->getTotalRowCount()); 

API文档:https://github.com/Factual/factual-php-driver/wiki/Total-Row-Count

##排序结果 Factual将根据字段逐个为您排序查询结果。简单示例

    // Build a Query to find 10 random entities and sort them by name, ascending:
    $query = new FactualQuery;
    $query->limit(10);
    $query->sortAsc("name");
    $res = $factual->fetch("places", $query);
	print_r($res->getData());  

您可以指定多个排序,并且结果将按照第一个排序为主排序,第二个排序为次要排序,依此类推

    // Build a Query to find 20 random entities, sorted ascending primarily by region, then by locality, then by name:
	$query = new FactualQuery;
	$query->limit(10);
	$query->sortAsc("region");
	$query->sortAsc("locality");
	$query->sortDesc("name");
	$res = $factual->fetch("places", $query);
	print_r($res->getData());

按距离排序需要特殊的$distance操作符。请确保在PHP中转义美元符号

	$query->sortAsc("\$distance"); //order results 

阅读API文档:http://developer.factual.com/api-docs/#Read

维面

维面是一个特殊调用,它根据特定属性的值返回汇总行计数——将其视为SQL中的COUNT()和GROUP BY查询的组合。

使用维面通过计数分析查询结果:例如,您可能希望查询位于500m范围内的所有企业,按类别对这些企业进行分组,并获取每个类别的计数。

维面示例

//Finds the top twenty-five countries containing places with the string 'Starbucks'
$query = new FacetQuery("country"); //name the field to facet on in the constructor
$query->search("starbucks"); //search on 'Starbucks' using the usual paramateric filters
$query->limit(15); //show no more than 15 results
$query->minCountPerFacet(10); //only show countries with more than 10 results
$res = $factual->fetch("global", $query); //perform the query using Factual::fetch() as usual
print_r($res->getData()); //dump results out as an array

响应看起来像

Array
(
    [country] => Array
	(
	    [us] => 11019
	    [ca] => 902
	    [gb] => 434
	    [cn] => 194
	    [de] => 174
	    [tw] => 121
	    [ph] => 78
	    [au] => 69
	    [tr] => 68
	    [id] => 55
	    [fr] => 47
	    [sg] => 41
	    [mx] => 33
	    [ch] => 31
	    [hk] => 27
	)
)

您不能对所有字段进行维面,只能对Factual配置为维面的字段进行维面。使用模式调用确定哪些字段可以进行维面:如果模式的维面属性为true,则可以进行维面。

维面参数

参数 描述 示例
select 应生成维面的字段名称的逗号分隔字符串数组,作为FacetQuery构造函数的参数。响应的顺序不一定与该列表相同,也不会反映字段之间的任何嵌套关系。 $query = new FacetQuery("region,locality");
min_count 仅包含具有此最小计数的维面。必须是零或更大。默认值是1。 $query->minCountPerFacet(2)
limit 对于单个字段可以返回的唯一维面值的最大数量。范围是1-250。默认值是20。 $query->limit(10)

您还可以像任何其他Read查询一样使用维面、包含计数、地理和搜索参数。

维面API文档:http://developer.factual.com/api-docs/#Facets

#写入 提交端点允许您将记录添加到Factual,或更新现有记录。要删除记录,请参阅下面的flag()方法。

未经验证的账户被限制使用提交API调用。登录Factual,并在http://www.factual.com/keys/verify验证您的账户。

语法

严格来说,当您贡献数据时,我们执行的是'UPSERT'操作:我们确定实体是否已存在,并相应地更新它;如果不存在,则创建一个新实体。这可以避免重复,即使您不知道Factual ID,也能贡献数据。然而,如果您知道Factual ID,请使用FactualSubmittor::setFactualID()方法包含它,以消除任何歧义。更新现有记录和添加新记录之间的唯一区别就是包含Factual ID

	$submitterator->setFactualID("f33527e0-a8b4-4808-a820-2686f18cb00c");

您可以确定您提交的实体是否是新实体

	//is the submission a new entity?
	$isNew = $res->isNew();

但是,始终从提交结果中获取Factual ID,并将其存储在提交的实体上是一个好主意

	//get Factual ID of submitted entity
	$factualID = $res->getFactualID();

我们试图在每个提交结果中返回一个Factual ID;记录此信息并存储它,并与您提交的ID进行验证是一个好习惯。在少数情况下(例如,如果您提交的实体已被弃用),我们可能返回与您提交的不同的Factual ID。在非常有限的情况下,提交可能不会实时匹配到记录,因此不会提供任何factual_id。

提交参数

参数 描述 必填? 示例
user 代表提交数据的最终用户的任意令牌。最好是保持匿名;我们不希望知道您的用户是谁,但请使用此令牌来模拟和衡量他们各自贡献的质量 setUserToken("387523")
values 要提交的数据;表模式中的字段名称映射到值 setValue("locality","Palo Alto")
setValue("address","425 Sherman Ave.")
comment 任何可能有助于解释提交的英文文本注释 setComment("New Office")
reference 对URL、标题、人员或其他提交数据来源的引用 setReference("http://www.factual.com/contact/new")
strict 如果设置为true,Factual将拒绝包含无效字段的提交。(默认为false。)下面有更多内容。 strict=true
clear_blanks 如果设置为true,任何哈希到""的字段将被清除。请谨慎使用。(默认为false。)下面有更多内容。 strict=true

严格模式

默认情况下,Factual的API将乐观地接受values参数中提供的所有字段(除了明确标记为“不可写”的字段)。这使得将数据传递给Factual变得更容易,而不管这些数据与您正在修复的表的模式是否精确匹配。

但是,由于我们很酷、很时髦,我们引入了一个缺点:如果您提供的数据可能因字段名称与您在values参数中输入的内容不匹配而被丢弃,您将不会收到警告。例如,如果您将“category”误拼为“catogory”。

将strict参数设置为true将导致系统自动验证您提供的值的名称与Factual模式是否匹配。任何不匹配的字段将导致您的整个提交自动被拒绝,并返回400错误。

	//create submittor object and set strictMode to true
	$submitterator = new FactualSubmittor;
	$submitterator->strictMode(); //sets to true
	
	//set Factual ID and set new values
	$submitterator->setFactualID("03c26917-5d66-4de9-96bc-b12066172c65");
	$submitterator->setValue("locality","Salaberry-de-Valleyfield");    
	$submitterator->setValue("addresss","80 Rue Masson"); //this will bork the query b/c the field name is invalid
	
	//make request
	$res = $factual->submit($submitterator);

清除空值

默认情况下,Factual使用单独的调用来清除字段的信息。这是因为很容易发送空值,而实际上并没有真正打算清除相应的属性。使用clearBlanks()可以绕过此保护措施,以便可以在单个API调用中完成字段的清除。例如

	//create submittor object and set clearBlanks to true
	$submitterator = new FactualSubmittor;
	$submitterator->clearBlanks(); //sets to true
	
	//set Factual ID and set new values
	$submitterator->setFactualID("03c26917-5d66-4de9-96bc-b12066172c65"); //the Factual ID for our LA office
	$submitterator->setValue("locality","Salaberry-de-Valleyfield");    
	$submitterator->setValue("address","80 Rue Masson");
	$submitterator->setValue("address_extended","");
	
	//make request
	$res = $factual->submit($submitterator);

将表现得与发送带有名称、地址以及清除address_extended请求的提交请求相同,以更新地址并删除现有的扩展地址。

##延迟写入有时,如果很少,写入会被缓存而不直接写入。在这种情况下,既不会返回commitID也不会返回Factual ID。

由于这是预期(尽管不常见)的程序流程,最好使用isDelayed()方法检查提交内容。

//make request
$res = $factual->submit($submitterator);
if (!$res->isDelayed()){
	//store Factual ID and Commit ID
} else {
	//do omething else
}

##提交示例

向Factual的地点表添加数据

	//Create new submittor object and assign table to write to
	$submitterator = new FactualSubmittor;
	$tableName = "us-sandbox"; //the table we are writing to

	//add individual user token & table name (required)
	$submitterator->setUserToken("1235");   //this your assigned the token of the individual user
	$submitterator->setTableName($tableName); //the table name containing the record

	//add the values to update
	$submitterator->setValue("locality","Salaberry-de-Valleyfield");	
	$submitterator->setValue("address","80 Rue Masson");

	//this other metadata is optional, but welcome
	$submitterator->setComment("This is a test update");
	$submitterator->setReference("http://example.com/");

	//make request
	$res = $factual->submit($submitterator);

	//confirm status of submission
	if ($res->success()){
		if ($res->isDelayed){
			echo "OK, but delayed write\n";
		} else {
			echo "OK\n";
		}
	} else {
		echo "Borked\n";
	}

以数组形式添加数据
这与上一个示例做的是同样的事情,但参数是一个关联数组

	//Create new submittor object and assign table to write to
	$submitterator = new FactualSubmittor;
	$tableName = "us-sandbox"; //the table we are writing to

	//add individual user token & table name (required)
	$submitterator->setUserToken("1235");   //this your assigned the token of the individual user
	$submitterator->setTableName($tableName); //the table name containing the record

	//add the values to update
	$data = array(
		'locality' => "Salaberry-de-Valleyfield",
		'address' => "80 Rue Masson"
	);
	$submitterator->setValues($data);

	//this other metadata is optional, but welcome
	$submitterator->setComment("This is a test update");
	$submitterator->setReference("http://example.com/");

	//make request
	$res = $factual->submit($submitterator);

	//confirm status of submission
	if ($res->success()){
		echo "OK\n";
	} else {
		echo "Borked\n";
	}

确定Factual是否将您的提交视为新的实体
使用SubmitResponse::isNew()

	echo "New Response?:". (bool)$res->isNew();

更正Factual地点表中特定实体的经纬度

	//Create new submittor object and assign table to write to
	$submitterator = new FactualSubmittor;
	$tableName = "us-sandbox"; 

	//add individual user token & table name (required)
	$submitterator->setUserToken("1235");   //this your assigned the token of the individual user
	$submitterator->setTableName($tableName); //the table name containing the record

	$submitterator->setFactualID("03c26917-5d66-4de9-96bc-b13066173c65"); //the Factual ID for our LA office
	$submitterator->setValue("longitude",-118.41822);	
	$submitterator->setValue("latitude",34.06025);

	//make request
	$res = $factual->submit($submitterator);

更正Factual地点表中特定实体的商家名称

	//Create new submittor object and assign table to write to
	$submitterator = new FactualSubmittor;
	$tableName = "us-sandbox"; 

	//add individual user token & table name (required)
	$submitterator->setUserToken("1235");   //this your assigned the token of the individual user
	$submitterator->setTableName($tableName); //the table name containing the record

	//set values against specific Factual ID
	$submitterator->setFactualID("0cb6c5b0-cd40-012e-5616-003048cad9da"); //the Factual ID of the entity to change
	$submitterator->setValue("name", "W Austin");

	//make request
	$res = $factual->submit($submitterator);

向Factual地点表中的特定实体添加一个社区

	//Create new submittor object and assign table to write to
	$submitterator = new FactualSubmittor;
	$tableName = "us-sandbox"; 

	//add individual user token & table name (required)
	$submitterator->setUserToken("1235");   //this your assigned the token of the individual user
	$submitterator->setTableName($tableName); //the table name containing the record

	//set values against specific Factual ID
	$submitterator->setFactualID("0cb6c5b0-cd40-012e-5616-003048cad9da"); //the Factual ID of the entity to change
	$submitterator->setValue("neighborhood", "Downtown Austin");
		
	//make request
	$res = $factual->submit($submitterator);

从Factual地点表中的特定实体删除一个社区

	//Create new submittor object and assign table to write to
	$submitterator = new FactualSubmittor;
	$tableName = "us-sandbox"; 

	//add individual user token & table name (required)
	$submitterator->setUserToken("1235");   //this your assigned the token of the individual user
	$submitterator->setTableName($tableName); //the table name containing the record

	//set values against specific Factual ID
	$submitterator->setFactualID("0cb6c5b0-cd40-012e-5616-003048cad9da"); //the Factual ID of the entity to change
	$submitterator->removeValue("neighborhood"); //yoink
		
	//make request
	$res = $factual->submit($submitterator);	

提交API文档:http://developer.factual.com/api-docs/#Submit 地点提交API文档:http://developer.factual.com/write-api/

##标记数据以供编辑关注 标记功能为开发人员和编辑团队提供了在Factual表中“标记”问题实体的能力,以便进行编辑审查。使用此功能请求删除实体、标记实体为重复或垃圾邮件、注明其不存在,或只是要求Factual编辑检查它。

标记示例

	//get started
	require_once('Factual.php');
	$factual = new Factual($key,$secret);
	//create a new flagger object to hold our parameters
	$flagger = new FactualFlagger;
	//add required parameters
	$flagger->setFactualID("f33527e0-a8b4-4808-a820-2686f18cb00c"); //ID to check
	$flagger->setTableName("2EH4Pz"); //name of table
	$flagger->setUserToken("testUser"); //arbitrary token of individual user
	$flagger->setProblem("duplicate");
	//add optional parameters
	$flagger->setComment("Found by user");
	$flagger->setReference("Original entity on http://example.com");
	//make request
	$res = $factual->flag($flagger);
	//check for success
	if ($res->success()){
		echo "OK\n";
	} else {
		echo "Borked\n";
	}

标记API文档:http://developer.factual.com/api-docs/#Flag

##清除属性值 Clear()方法允许您清除或从Factual记录中删除属性值。

清除参数

参数 描述 必填? 示例
user 代表提交数据的最终用户的任意令牌。 $clear->setUserToken("twb")
fields 要清除的属性字段。 $clear->clearValues(array("longitude","latitude")) 或 $clear->clearValue("name")
comment 任何可能帮助解释清除/提交的文本。请仅使用英文。 $clear->setComment("通过电子邮件由所有者提交");
reference 对URL、标题、人物等来源的引用,这些是提交数据的来源。 setReference("http://www.factual.com/contact/new")

清除示例

清除现有实体中经纬度的值

	//create clearor object
	$clearor = new FactualClearor;
	
	//assign the ID and se the values to clear/wipe
	$clearor->setFactualID("1d93c1ed-8cf3-4d58-94e0-05bbcd827cba");//this is required
  	$clearor->clearValue("longitude");
  	$clearor->clearValue("latitude");
  	
  	//set tablename and other metadata about this submission
  	$clearor->setTableName("us-sandbox"); //where can we find this entity
  	$clearor->setUserToken("8363b7"); //the user/editor who is writing to us through you
  	
	//make request
	$res = $factual->clear($clearor);

作为替代,您可以使用clearValues()清除多个属性

	$values = array("longitude","latitude");
	$clearor->clearValues($values);

清除API文档:http://developer.factual.com/api-docs/#Clear

交叉引用

Factual的交叉引用功能允许您通过查看其他网络权威机构的URL来“交叉引用”网络。

请注意,从v1.4.3版本开始,交叉引用请求被视为任何其他表的读取操作——这意味着您可以使用正常搜索和过滤器访问交叉引用表,如下面的示例所示。从v.1.5.0版本开始,所有过时的交叉引用功能都已删除。

地点交叉引用示例

    // Get all Crosswalk data for a specific Place, using its Factual ID:
    $query = new FactualQuery;    
	$query->field("factual_id")->equal("97598010-433f-4946-8fd5-4a6dd1639d77");	 
	$res = $factual->fetch("crosswalk", $query);
	print_r($res->getData());

交叉引用API文档:http://developer.factual.com/places-crosswalk/

#匹配Factual的匹配功能允许您将您自己的数据与Factual的数据进行匹配。如果我们确信匹配,我们将返回匹配实体的ID(仅ID)。

如果您希望使用匹配数据丰富您的实体,请参阅Factual Resolve。此服务专为高容量实体匹配而设计。匹配功能几乎与Resolve相同,但我们只返回Factual ID,并且查询不计入用户的配额。

通常,您提供的服务信息越多,我们越能准确地匹配。

找到匹配项

使用常见的查询结构将已知属性添加到查询中

    //Build the query
	$query = new MatchQuery();
	$query->add("name", "Buena Vista Cigar Club");
	$query->add("latitude", 34.06);
	$query->add("longitude", -118.40);
	//perform the query
	$res = $factual->fetch("places", $query);

然后查看是否找到匹配项

	$match = $res->getMatched()); //FALSE == no match, Factual ID == match	

快捷方法

或者使用事实对象中的快捷方法

	//assing tablename
	$tableName = "places";
	//create values array
	$vars = array(
		"name"=>"Buena Vista Cigar Club",
		"latitude"=>34.06,
		"longitude"=>-118.40
	);
	$res = $factual->match($tableName,$vars);
	$match = $res->getMatched()); //FALSE == no match, Factual ID == match	

匹配API文档: http://developer.factual.com/api-docs/#Match

#解析 使用解析将您的数据与Factual的进行匹配:我们返回我们关于实体的所有信息,以便您丰富或去重您的内容。

请注意,我们提供了一个返回Factual ID的单独端点:Factual匹配,如上所述。当您想要以高容量将Factual ID附加到实体并调用配额时,请使用匹配;当您想要用我们的数据丰富实体时,请使用解析。

解析示例

使用常见的查询结构将已知属性添加到查询中

    // Get all entities that are possibly a match
	$query = new ResolveQuery();
	$query->add("name", "Buena Vista Cigar Club");
	$query->add("latitude", 34.06);
	$query->add("longitude", -118.40);
	$res = $factual->fetch("places", $query);	

然后使用结果对象上的方法来确定解析

    //Did the entity resolve? (returns bool)
    $isResolved = $res->isResolved();
    
    //If so, get it:
    $resolvedEntity = $res->getResolved();

快捷方法

或者使用快捷方式返回解析后的实体或null(如果没有解析)

	//Resolve and return
	$tableName = "places";
	$vars = array(
		"name"=>"Buena Vista Cigar Club",
		"latitude"=>34.06,
		"longitude"=>-118.40
	);
	$res = $factual->resolve($tableName,$vars);
	print_r($res->getResolved()); //FALSE == no match, Array of entity data == resolved

解析API文档: http://developer.factual.com/api-docs/#Resolve

世界地理

虽然Factual的地点表提供了对世界商业和地标访问,但我们的世界地理表提供了对250个国家超过520万个地理区域以及830万个名称变体的结构化访问。使用我们的世界地理表查找地名,查看一个地点如何与另一个地点相关联,以及在多种语言之间翻译地名。

世界地理示例

	//find all localities (towns and cities) called "Wayne" in the US 
	$query = new FactualQuery;
	$query->field("name")->equal("wayne");
	$query->field("country")->equal("us");
	$query->field("placetype")->equal("locality");	//we don't want counties, etc.
	$query->only("name,placetype,longitude,latitude"); //"take only what you need from me.."(singing)
	$res = $factual->fetch("world-geographies", $query);
	print_r($res->getData()); 

世界地理数据文档: http://www.factual.com/products/world-geographies

地点分类

所有Factual地点都被分类到400多个类别中的一个。

按类别搜索

搜索category_id字段

	$category = "107"; //landmarks
	$query = new FactualQuery;	
	$query->field("category_ids")->in($category); //retrieves this category and all its descendants
	$res = $factual->fetch("places-us", $query); 	
	print_r($res->getData());

地点分类文档: http://developer.factual.com/working-with-categories/

全球产品

Factual全球产品为美国超过50万个最受欢迎的消费包装商品提供详细的产品数据,包括您最喜欢的健康、美容、食品、饮料和家用产品。通过全球产品,您可以访问关键产品属性,使用强大的搜索工具或UPC查找产品,并连接到网络上的产品页面。有关此完全运行的战斗站点的详细信息,请参阅全球产品API文档

全球产品示例

	$tableName = "products-cpg";

	//Search for products containing the word "shampoo"
	$query = new FactualQuery;
	$query->search("shampoo");
	$res = $factual->fetch($tableName, $query); 
	print_r($res->getData());
	
	//Same search as above, but filter the search results to include only the brand "pantene"
	$query = new FactualQuery;
	$query->search("shampoo");
	$query->field("brand")->equal("pantene"); //don't hate me because I'm beautiful
	$res = $factual->fetch($tableName, $query); 
	print_r($res->getData());	
	
	//Same search as above, with added filter for products that are 12.6 oz.
	$query = new FactualQuery;
	$query->search("shampoo");
	$query->field("brand")->equal("pantene");
	$query->field("size")->search("12.6 oz"); //we use 'search' b/c sometime it is 'fl oz' or just 'oz'
	$res = $factual->fetch($tableName, $query); 
	print_r($res->getData());	
	
	//Search on UPC
	$query = new FactualQuery;
	$query->field("upc")->equal("052000131512"); 
	$res = $factual->fetch($tableName, $query); 
	print_r($res->getData());
	
	//Find all beverages (filter by category)
	$query = new FactualQuery;
	$query->field("category")->equal("beverages"); 
	$res = $factual->fetch($tableName, $query); 
	print_r($res->getData());	
	
	//Count all beverage products
	$query = new FactualQuery;
	$query->field("category")->equal("lip makeup"); 	
	$query->includeRowCount(); //this tells the API to calculate this value (modest overhead)
	$res = $factual->fetch($tableName, $query); 
	print_r($res->getTotalRowCount());	

#原始请求此驱动程序主要提供便利:它签名请求,构建符合规范的查询,并结构化响应。

然而,我们确实提供了一个选项,其中PHP驱动程序将执行OAuth身份验证和参数编码,允许您将“原始”键/值参数传递给我们的API进行调试,实现驱动程序中尚未编码的API功能,或者简单地满足自虐倾向。

这些方法签名、编码并提交请求。响应是原始JSON,而不是Factual响应对象。

原始GET

用于所有GET操作,基本上是所有查询和对Factual服务的其他只读调用。

	//Raw Get Test
	$path = "t/global";
	$params['filters'] = "{\"\$and\":[{\"country\":{\"\$eq\":\"CA\"}},{\"locality\":{\"\$eq\":\"Toronto\"}}]}";
    $params['limit'] = 50;
    $params['include_count'] = true;
	$res = $factual->rawGet($path,$params);
	print_r($res);

在上面的示例中,我们转义了JSON以便它能够解析。作为一种既机智又较长的替代方法,你可以创建一个嵌套数组作为过滤器,并对其进行json编码,从而避免需要对JSON字符串进行转义

	//create each filter as an array
	$countryFilter = array (
			'country'=> array (
				'$eq'=>"CA"
			)
		);
	$localityFilter = array (
			'locality'=> array (
				'$eq'=>"Toronto"
			)
		);		
	//combine filters
	$filter = array(
		'$and' => array($countryFilter,$localityFilter)	
	);
	$params['filters'] = json_encode($filter); //json encode

但是,通常情况下,请坚持使用参数化过滤器方法;原始请求模式主要用于调试。

##原始POST用于所有POST操作:主要用于提交和标记API。

	//Raw POST Test
	$path = "t/2EH4Pz/f33527e0-a8b4-4808-a820-2686f18cb00c/flag";
	$post['user'] = "testUser";
	$post['problem'] = "spam";
	$post['comment'] = "What do you mean 'Urgghh'? I don't like spam!";
	$res = $factual->rawPost($path,$post);
	print_r($res);

##提升Boost API帮助Factual解决HTTP的无状态问题,以改善搜索结果。它允许你向Factual表明,在读取API调用中的全文搜索返回的特定行应该是对该搜索的突出结果。指定的行Factual ID不需要在读取请求的响应中。例如,你可以使用提升来表明你希望的结果(通过其Factual ID识别)是首选的。

此代码在搜索之后进行。你需要将查询保存在用户会话或类似的地方

  $factual = new Factual($key,$secret); 
	$boost = new FactualBoost; //create the boost object for populating
	$boost->setQueryString("chipotle palo alto"); //use for free text queries only
	$boost->setUserToken("user1234"); //anon. user token for this session. Optional, but helps us if poss.
	$boost->setFactualID("71df2b80-bef8-012e-5614-003048cad9da"); //the ID of the entity selected by the user
	$boost->setTableName("places-us"); //table the query was made against
	$res = $factual->boost($boost);
	//test for success. Just for debugging, of course.
	if ($res->success()){
		echo "Boosted";
	} else {
		echo "Borked";
	}

请注意,Boost API不会导致实时搜索结果的改进或用户自定义的搜索体验。Boost简单允许通过Factual API长期增强整体搜索结果质量。

Boost API文档:[http://developer.factual.com/api-docs/#Boost](http://developer.factual.com/api-docs/#Boost)

##差异Diffs API由Factual提供,用于我们的数据下载合作伙伴——那些使用Factual数据完整副本进行远程操作的人。Diffs API为远程数据集产生原子的JSON更新。有关完整概述,请参阅Factual Diffs API文档。

单个差异

单个差异由一个完整的JSON数组组成。差异馈送是一系列封装的差异。单个差异

Array
(
    [factual_id] => 0249bc16-8912-4653-81a5-e07e0964c343
    [type] => update
    [payload] => Array
        (
            [region] => ON
            [geocode_accuracy] => 7.5
            [fax] => (416) 781-2744
            [website] => http://www.tasco.net
            [tel] => (416) 781-9145
            [postcode] => M6B 3T8
            [country] => ca
            [category] => Services and Supplies > Home Improvement > Home Appliances
            [address] => 11160 Yonge St
            [name] => Tasco Distributors
            [locality] => Richmond Hill
            [longitude] => -79.4543685913
            [latitude] => 43.7132034302
        )
    [changed] => Array
        (
            [0] => tel
        )
    [timestamp] => 1339136961334
)

有效载荷包含整个记录,而更改元素仅突出显示已更改的项目。

获取差异

	//Getting started
	require_once('Factual.php');
	$factual = new Factual($key,$secret);

	//Getting Diffs
	$query = new DiffsQuery;
	$query->setStart(1339123455775); //starting time for updates window. Milliseconds timestamp.
	//$query->setEnd(1339136968687); //this is optional. Otherwise defaults to current time
	$res = $factual->fetch("2EH4Pz", $query);	//run query

运行Diffs查询后,你可以对结果对象执行以下操作

处理差异响应对象

获取汇总统计信息

	//show summary stats
	print_r($res->getStats());

返回更新计数和窗口持续时间的概述

Array
(
    [insert] => 78
    [update] => 705
    [delete] => 56
    [deprecate] => 0
    [total] => 839
    [duration] => 09:35:19
	[start] => Thu, 07 Jun 2012 19:44:15 -0700
	[end] => Sun, 29 Jul 2012 01:20:13 -0700
)

遍历差异

结果对象是一个ArrayIterator,因此你可以遍历结果

	foreach ($res as $diff){
		print_r($diff);
	}

逐个输出差异作为数组。你可以获取所有差异作为差异数组的数组

	$allDifs = $res->getDiffs();

获取开始和结束窗口时间

结果对象提供了一些额外的方法,用于确定差异窗口的具体开始、结束和持续时间时间戳

	$end = $res->getEnd() //get close of window as timestamp
	$duration = $res->getDuration() //get duration of window as timestamp
	$start = $res->getStart() //get start of window as timestamp

将true作为参数以获取可读版本

	$end = $res->getEnd(true) //get close of window as human-readable RFC 2822
	$duration = $res->getDuration() //get duration of window as H:m:s
	$start = $res->getStart() //get start of window as tRFC 2822

Diffs API文档:[http://developer.factual.com/api-docs/#Diffs](http://developer.factual.com/api-docs/#Diffs)

##多查询我们的“多”功能允许你通过单个HTTP请求进行最多三个查询。多可以组合不同类型的查询,但它们都必须是GET请求。有关详细信息,请参阅[多API文档](http://developer.factual.com/display/docs/Core+API+-+Multi)。

多示例

像往常一样创建查询对象,并使用multiQueue()将它们添加到查询队列中

	//create first query and add to queue
	$query1 = new FactualQuery;
	$query1->limit(3);
	$query1->only("factual_id,name");
	$factual->multiQueue("global", $query1, "globalQ"); //'globalQ' is the arbitrary handle for this query

	//create second query and add to queue
	$query2 = new FactualQuery;
	$query2->limit(3);
	$query2->only("factual_id,name");
	$factual->multiQueue("world-geographies", $query2, "worldGeo"); //'worldGeo' is the arbitrary handle for this query

请注意,multiQueue()参数与fetch()方法类似,但包括一个必需的第三个参数:一个任意字符串,你用它来标识每个查询的结果。这些必须对每个查询都是唯一的。

使用multiFetch()发送你的请求

	//make multi request
	$res = $factual->multiFetch();

并遍历响应以获取每个响应对象

	//iterate through response objects
	foreach ($res as $queryResponse){
	    print_r($queryResponse->getData());
	} 

多API文档: http://developer.factual.com/api-docs/#Multi

与Factual数据文件协作一些Factual数据合作伙伴与我们合作数据滴而不是API。Factual数据文件以压缩、制表符分隔的格式提供,文件名包含毫秒UNIX时间戳,例如

us_places.developer_preview.1345052880000.tab.gz

压缩格式为gzip -- 它可以用大多数Windows、Linux和Mac压缩工具打开。

此时间戳应用于您的第一个 Diffs API 调用。

文件大小

Factual文件包含数百万条记录。如果您尝试使用Excel,请不要这样做。不要将整个文件加载到内存中,也不要尝试用编辑器查看 - 使用head、tail、sed、awk、grep和其他工具。这些在Windows上都可以在 http://gnuwin32.sourceforge.net/ 获取

加载到SQL或其他系统

使用fgetcsv命令将数据加载到数据库中相当简单

	//get file pointer
	filename = "path/to/data/file";
	$fp = fopen($filename, "r");
	
	//iterate row-by-row
	while ($row = fgetcsv($fp,0, $delimiter)){
		//$row is now your first row of data
		// insert ROW into your db w/ SQL
	}

确定字段宽度

Factual在字段长度方面没有正式的规范 -- 总是有可能在版本之间字段长度会发生变化(但很少变化很大)。然而,我们提供了一种 CSV分析脚本,允许您计算任何CSV的值长度。

如果您在Windows上,并且不想运行PHP脚本,可以使用 第三方Windows实用工具 来完成相同的事情。

#Wordpress关于如何将Factual PHP驱动作为Wordpress插件安装的简要说明

  1. 从Factual下载驱动程序的 zip存档 或从 https://github.com/Factual/factual-php-driver git clone,然后自行 zip存档

  2. 转到Wordpress管理器的 插件页面 (/wordpress/wp-admin/plugins.php)

  3. 点击 添加新插件

  4. 点击 上传

  5. 选择驱动程序的.zip存档(注意:插件管理器只接受.zip文件)

  6. 点击 激活插件

  7. 创建一个测试页面,例如

     <html>
     <body>
     <?php
     /** load factual driver. Make sure the path below matches what you have! */
     require_once('./wp-content/plugins/factual-php-driver-master/Factual.php');
     $factual = new Factual("YOUR_API_KEY","YOUR_API_SECRET");
     $query = new FactualQuery;
     $res = $factual->fetch("places-us", $query);
     $data = $res->getData();
     ?>
     <h1>Hello. I found a place at:
     <?php>
     /** print the address of the first place */
     print_r($data[0][address]);
     ?>
     </h1>
     </body>
     </html>
     
  • 确保在创建$factual对象时已输入您自己的 密钥密钥
  • 确保导入路径与您的插件路径相匹配。
  • 您需要将一个带有US邮编的 zip 参数传递到URL中。

如果一切顺利,您应该得到如下所示的内容

Hello World Screenshot!