PHP JSON解析,缺少项目

时间:2013-01-13 04:55:58

标签: php json

当我在浏览器中输入URL时,我得到输出(下图)

{"categories":[{"id":"16","name":"Arm Locks"},{"id":"555","name":"Articles"},{"id":"19","name":"Back Control"},{"id":"21","name":"Brazilian Jiu Jitsu"},{"id":"12","name":"Chokes"},{"id":"15","name":"Crank"},{"id":"14","name":"Escapes"},{"id":"554","name":"Grappling Videos"},{"id":"10","name":"Guard and Rubber Guard"},{"id":"13","name":"Guard Breaks"},{"id":"23","name":"Half Guard"},{"id":"26","name":"Japanese Jujutsu"},{"id":"1","name":"Jiu Jitsu Training"},{"id":"5","name":"Jiu Jitsu Videos"},{"id":"25","name":"Leg Locks"},{"id":"27","name":"MMA"},{"id":"17","name":"Mount"},{"id":"30","name":"North South Position"},{"id":"556","name":"Platinum Members Only"},{"id":"29","name":"Self Defense"},{"id":"18","name":"Side Control"},{"id":"28","name":"Strikes"},{"id":"11","name":"Sweeps"},{"id":"20","name":"Theory & Discussions"},{"id":"9","name":"Throws"},{"id":"31","name":"Wrestling"},{"id":"22","name":"Wrist Locks"}]}

但是当我尝试使用PHP(PHP代码和输出)进行解析时

PHP代码

<?php
$url = "https://domain.com/apis/cats.php?type=json";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
$dcjsn = json_decode($json);

foreach ($dcjsn->categories as $cat){
    echo $cat->id;
    echo "<br>";
}

输出为:

555
15
14
554
13
23
26
25
27
17
30
29
18
28
20
9
22

意味着大约有10件物品丢失了!

我无法识别代码中的错误。我也尝试过使用file_get_contents(),但没有运气。

增加:

var_dump($ json)

的结果
string(574) "{"categories":[{"id":"555","name":"Articles"},{"id":"15","name":"Crank"},{"id":"14","name":"Escapes"},{"id":"554","name":"Grappling Videos"},{"id":"13","name":"Guard Breaks"},{"id":"23","name":"Half Guard"},{"id":"26","name":"Japanese Jujutsu"},{"id":"25","name":"Leg Locks"},{"id":"27","name":"MMA"},{"id":"17","name":"Mount"},{"id":"30","name":"North South Position"},{"id":"29","name":"Self Defense"},{"id":"18","name":"Side Control"},{"id":"28","name":"Strikes"},{"id":"20","name":"Theory & Discussions"},{"id":"9","name":"Throws"},{"id":"22","name":"Wrist Locks"}]}"

1 个答案:

答案 0 :(得分:4)

您正在请求的API似乎需要身份验证,而您在浏览器中时却没有从PHP代码登录。