且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从API获取数据-PHP-curl

更新时间:2023-02-21 21:23:25

尝试调试的一种好方法是检查curl信息数组或curl错误.

A good way to try and debug this would be to check the curl info array, or curl error.

<?php
/**
 * Handles making a cURL request
 *
 * @param string $url         URL to call out to for information.
 * @param bool   $callDetails Optional condition to allow for extended       
 *   information return including error and getinfo details.
 *
 * @return array $returnGroup cURL response and optional details.
 */
function makeRequest($url, $callDetails = false)
{
  // Set handle
  $ch = curl_init($url);

  // Set options
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Execute curl handle add results to data return array.
  $result = curl_exec($ch);
  $returnGroup = ['curlResult' => $result,];

  // If details of curl execution are asked for add them to return group.
  if ($callDetails) {
    $returnGroup['info'] = curl_getinfo($ch);
    $returnGroup['errno'] = curl_errno($ch);
    $returnGroup['error'] = curl_error($ch);
  }

  // Close cURL and return response.
  curl_close($ch);
  return $returnGroup;
}

$url = /* some url */
$response = makeRequest($url, true);

// Check your return to make sure you are making a successful connection.
echo '<pre>';
print_r($response);
?>

看看您是否成功建立了连接,然后确切地从响应中获得了什么,应该使您更好地了解如何处理它.

Seeing if you are successfully making the connection, and then also exactly what you are getting back in the response should give you a better idea of how to handle parsing it.

编辑

看起来有些非JSON字符串数据正在阻止json_decode函数正常工作.这不理想,但是确实发生了.在这种特定情况下,以下方法应该会有所帮助,但这只是解决涉及不良数据的问题的解决方法.

It looks like there is some non-JSON string data that is preventing the json_decode function from working. This is less than ideal, but it happens. Following method should help in this specific case, but is just a workaround to an issue involving bad data.

// continuing from above :) formatted for readability

/**
 * Separates JSON string from unnecessary data, parses into
 * an object and returns.
 *
 * @param string $curlResult String returned from cURL call.
 *
 * @return object $jsonObject Parsed JSON object. 
 */
function cleanJsonString($curlResult) {
  // Separates result string into array at " = ".
  $responseChunks = explode(" = ", $curlResult);

  // Removes semicolon from end of JSON string.
  $jsonString = substr($responseChunks[1], -1);

  // Parse JSON string into object.
  $jsonObject = json_decode($jsonString);

  return $jsonObject;
}

// Clean result.
$jsonObject = cleanJsonString($response['curlResult']);

// Print image object property.
echo $jsonObject->image;