【问题标题】:Parsing JSON output from API [duplicate]解析来自 API 的 JSON 输出 [重复]
【发布时间】:2016-02-24 21:41:57
【问题描述】:

我知道这个问题已经被问过很多次了,所以模组请不要关闭它,因为过去的答案都没有用,而且我已经搜索过了!所以我正在使用 HaveIBeenPwned API,它输出显然是 JSON 的内容,如下所示:

[
 {
  "Title":"000webhost"
  ,"Name":"000webhost"
  ,"Domain":"000webhost.com"
  ,"BreachDate":"2015-03-01"
  ,"AddedDate":"2015-10-26T23:35:45Z"
  ,"PwnCount":12345678
  ,"Description":"In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords."
  ,"DataClasses":[
    "Email addresses"
    ,"IP addresses"
    ,"Names"
    ,"Passwords"
  ]
  ,"IsVerified":true
  ,"IsSensitive":false
  ,"LogoType":"png"
 }
]

如果我使用以下内容,这就是输出:

echo $output;

json_decode($output) 不起作用。使用 foreach($output as $key) 不起作用,如果我使用它,它会说无效参数。我尝试了一个正常的for() 循环,但又没有任何乐趣。这个输出有什么问题?我如何获得其中的价值?你应该可以看出我正在使用 PHP。

【问题讨论】:

    标签: php json parsing


    【解决方案1】:

    使用json_decode($output, true);

    第二个参数定义结果数据格式——对象(false,默认)或关联数组(true)。

    【讨论】:

    • 不,恐怕我刚刚得到 - 注意:第 27 行 C:\xampp\htdocs\havei\index.php 中的数组到字符串转换。我用了你告诉我的,有一些有问题,只是似乎不想输出它。
    • 例如,如果我使用 $fs = json_decode($output, true); 然后尝试 echo $fs['Title'] 我只是得到另一个错误:注意:未定义的索引:第 28 行 C:\xampp\htdocs\havei\index.php 中的标题
    • 用您的代码示例更新您的问题,以便我们回答您的问题
    • 好吧,如果 print_r($fs); ?
    • 我认为你需要 $fs[0]['Title'];在你的情况下,因为你的 json 字符串以 [
    猜你喜欢
    • 2016-10-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 2015-08-05
    • 2013-05-31
    • 2017-07-05
    • 2021-03-21
    • 2019-03-08
    相关资源
    最近更新 更多