2013-11-01 129 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; 
相關問題