2013-11-01 85 views
4

我期待从CrunchBase API中获取公司列表的数据,然后将该数据添加到数据库中的选定表中。我真的不知道从哪里开始。我一直在看cURL。如何获取API数据并使用PHP将其添加到数据库中?

我在哪里,在现在:

$url = "http://api.crunchbase.com/v/1/company/audible-coffee.js?api_key=API_KEY&callback=?"; 
$data = get_data($url); 
// Note: ideally you should use DOM manipulation to inject the <base> 
// tag inside the <head> section 
$data = str_replace("<head>", "<head><base href=\"$url\">", $data); 
echo $data; 


function get_data($url) { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    curl_close($ch); 
    return $data; 
} 

我想我现在应该分析它,然后将数据存储在数据库中。

我努力找到解析数据,代码如下:

$json_string = '<url.json>'; 

$jsondata = file_get_contents($json_string); 
$obj = json_decode($jsondata, true); 
print_r($obj['Result']); 

不幸的是,我不知道我在做什么等什么改变或在任何输入从这里将去非常感谢。

+0

作为Cameeob2003指出的那样,你的'$ data'变量是不确定的。如果您的'error_reporting'设置为开发设置正确,您应该在屏幕上收到警告。考虑切换到一个报告未定义变量的IDE - NetBeans对此非常有用。 – halfer

回答

5

简单多了 - 直接访问URL,并且不与理会卷曲:

$url = "http://api.crunchbase.com/v/1/company/audible-coffee.js?api_key=API_KEY&callback=?"; 
$jsondata = file_get_contents($url); 
$obj = json_decode($jsondata); 

我这里假设你的问题的URL是保证返回JSON字符串的API。我不明白第一个代码示例中str_replace的用途。

1

要根据您提供的cURL方法回答您的问题,您在运行卷曲函数时并未将任何数据保存到$data变量中。这可以防止你有任何回报。

修正:

$url = "http://api.crunchbase.com/v/1/company/audible-coffee.js?api_key=API_KEY&callback=?"; 
$data = get_data($url); 
// Note: ideally you should use DOM manipulation to inject the <base> 
// tag inside the <head> section 
$data = str_replace("<head>", "<head><base href=\"$url\">", $data); 
echo $data; 

function get_data($url) { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

正如你可以看到上面我所说curl_close($ch);之前我节省curl_exec($ch);返回到$data。现在,我在屏幕上显示文本“Developer Inactive”(我自己并没有API密钥)。所以,现在当我返回$data变量时,我可以根据自己的情况操纵回报。

+0

好点,我没有看到'$ data'甚至没有设置! – halfer

0

你也可以试试......

header("Content-type: application/xml"); 
    $token="AUTHTOKEN"; 
    $url = "http://api.crunchbase.com/v/1/company/audible-coffee.js?api_key=API_KEY&callback=?"; 
    $param= "authtoken=".$token."; 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $param); 
    $result = curl_exec($ch); 
    curl_close($ch); 
    echo $result; 
    return $result; 
相关问题