php curl获取json并解码,然后显示,失败时不显示任何内容
您好,我的老师给了我这周的工作,我需要从url获取json数据,并使用json_decode将其显示为php,我使用url访问的php json文件将歌曲显示为json数组,工作正常,我复制了我的教师示例来访问url,但它无法显示我做错了什么 编辑:我确实需要输入密码和用户名才能访问url,所以我按说明更改了代码,但仍然没有显示任何内容。为了安全起见,我更改了密码和用户名,但格式和长度相同php curl获取json并解码,然后显示,失败时不显示任何内容,php,json,curl,Php,Json,Curl,您好,我的老师给了我这周的工作,我需要从url获取json数据,并使用json_decode将其显示为php,我使用url访问的php json文件将歌曲显示为json数组,工作正常,我复制了我的教师示例来访问url,但它无法显示我做错了什么 编辑:我确实需要输入密码和用户名才能访问url,所以我按说明更改了代码,但仍然没有显示任何内容。为了安全起见,我更改了密码和用户名,但格式和长度相同 <?php $username = "2foobar90"; $password = "123456
<?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/>";
}
?>
该链接需要基本身份验证。当您单击链接时,浏览器会记住您的用户名/密码。您可以使用chrome inspector查看请求标题
curl_setopt($connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($connection, CURLOPT_USERPWD, $username . ":" . $password);
请注意,这两个文件位于同一服务器上的同一文件夹中。