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

4
我希望能从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']);

很不幸,我不知道自己在做什么,所以非常感谢任何关于应该如何改变或下一步该去哪里的建议。


正如Cameeob2003所指出的那样,您的$data变量未定义。如果您的error_reporting设置正确,开发过程中应该会在屏幕上收到警告。考虑切换到一个报告未定义变量的IDE - NetBeans非常适合这个任务。 - halfer
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是一个API,保证返回JSON字符串。我不理解你第一段代码示例中str_replace的目的。

1
根据您提供的 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 中。现在我在屏幕上看到文本 "Developer Inactive"(我自己没有 API 密钥,我假设是这个原因)。所以,现在当我返回 $data 变量时,我可以按照自己的需要操作返回结果。


好眼力,我没看到$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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接