dongsu1951 2017-10-03 18:08 采纳率: 0%
浏览 169
已采纳

php curl获取json并解码然后显示,失败显示任何内容

hello my teacher has given me this weeks work and i need to get my json data from a url and display it as php using json_decode, the php json file which i access with the url displays the songs as an json array and works fine, and i copied my teachers curl example to access the url, but it fails to display anything what have i done wrong ?

Edit: i do need to enter a password and username to access the url so i changed the code as told, but still nothing displays, i changed the password and username for security but the format and length are the same

<?php
$username = "2foobar90";
$password = "123456";
// Initialise the cURL connection
$connection = curl_init();

curl_setopt($connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($connection, CURLOPT_USERPWD, $username . ":" . $password);  
// Specify the URL to connect to - DOUBLE CLICK link to test 
curl_setopt($connection, CURLOPT_URL, "https://edward2.solent.ac.uk/~martine/year3/hits.php?artist=David+Bowie");


// This option ensures that the HTTP response is *returned* from curl_exec(),
// (see below) rather than being output to screen.  
curl_setopt($connection,CURLOPT_RETURNTRANSFER,1);

// Do not include the HTTP header in the response.
curl_setopt($connection,CURLOPT_HEADER, 0);

// Actually connect to the remote URL. The response is 
// returned from curl_exec() and placed in $response.
$response = curl_exec($connection);

// Close the connection.
curl_close($connection);

$data = json_decode($response, true);

for($i=0; $i<count($data); $i++)
{
    echo "Song id " . $data[$i]["songid"] . " " .
         "Title " . $data[$i]["title"] . " " .
         "Artist " . $data[$i]["artist"] . " " .
         "Chart position " . $data[$i]["chart"] . "<br/>";
}
?>
  • 写回答

1条回答 默认 最新

  • doujugu1722 2017-10-03 18:20
    关注

    The link requires basic authentication. Your browser remembers your username/password when you click the link. You can see request headers with chrome inspector.

    1. Click link
    2. Open your browser inspector
    3. Click Network section
    4. Find document
    5. You can see Authorization data under the Request Headers

    enter image description here

    If you want to use authorization with curl add this:

    curl_setopt($connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($connection, CURLOPT_USERPWD, $username . ":" . $password);  
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?