如何使用 PHP 提取 API 数据并将其添加到数据库中


How to pull API data and add it into a database with PHP?

我希望从CrunchBase API中提取公司列表的数据,然后将该数据添加到数据库中的选择表中。我真的不知道从哪里开始。我一直在看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);
  curl_close($ch);
  return $data;
}

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

我为查找解析数据的代码所做的工作如下:

$json_string = '<url.json>';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
print_r($obj['Result']);

不幸的是,我不知道我在做什么,所以任何关于要改变什么或从这里开始的意见将不胜感激。

更简单 - 直接访问 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的目的。

要根据您提供的 cURL 方法回答您的问题,您在运行 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.现在我在屏幕上看到文本"开发人员不活动"(我自己没有 API 密钥)。所以现在当我返回$data变量时,我可以按照我认为合适的方式操作返回。

你也可以试试...

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;