4

I am looking to pull data for a list of companies from CrunchBase API, then add that data into select tables in a database. I really don't know where to start. I have been looking at cURL.

Where I am at right now:

$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;
}

I think I am supposed to parse it now, then store the data in the database.

My efforts to find code on parsing the data is the following:

$json_string = '<url.json>';

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

Unfortunately, I don't know what I'm doing so any input on what to change or where to go from here will be very much appreciated.

4

3 回答 3

5

简单得多 - 直接访问 URL,而无需使用 cURL:

$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您的第一个代码示例中的目的。

于 2013-11-01T21:16:30.890 回答
1

要根据您提供的 cURL 方法回答您的问题,$data您在运行 curl 函数时不会将任何数据保存到变量中。这可以防止您获得任何回报。

固定的:

$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);into的返回$data现在我在屏幕上看到了“开发者不活跃”的文字(我假设我自己没有 API 密钥)。所以现在当我返回$data变量时,我可以按照我认为合适的方式操纵返回。

于 2013-11-01T21:35:49.283 回答
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;
于 2016-04-07T10:24:20.707 回答