【问题标题】:How to get data from an array inside json data php如何从json数据php中的数组中获取数据
【发布时间】:2014-08-12 17:30:06
【问题描述】:

我有以下 json 数据数组。当我尝试使用 for each 循环时,php 给我错误“stdClass 类的对象无法转换为字符串”。我想访问 authns 数组和 soa 数组中的名称服务器。我该怎么做呢?

stdClass Object ( 
    [error] => 
    [domain] => whoisdoma.net 
    [ip_address] => 108.162.199.120   
    [authns] => stdClass Object ( 
        [nameserver] => uma.ns.cloudflare.com 
        [ip] => 173.245.58.146 
        [location] => San Francisco 
    ) 
    [soa] => stdClass Object ( 
        [nameserver] => tom.ns.cloudflare.com 
        [email] => dns.cloudflare.com 
        [serial] => 2015505396 
        [refresh] => 10000 
        [retry] => 2400 
        [expiry] => 604800 
        [minimum] => 3600 
    )
) 

这是我用来获取数据的代码:

 <?php
 $domain = $_GET['domain'];
//set the url
$url = "http://api.site.ga/v1/dns/lookup?domain=".$domain;

//start a curl session
$ch = curl_init();
$timeout = 5;

//set curl options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

//get the data
$data = curl_exec($ch);

//decode the data
$jsonData = json_decode($data);

//close the curl session
curl_close($ch);

?>

这是我正在使用的每个循环

<?php 

foreach($jsonData->authns as $authns)
{
    echo $authns->nameserver;
}

?>

【问题讨论】:

  • 第一件事。你有没有使用json_decode()从json转换它?如果是这样,请尝试:$object-&gt;authns-&gt;nameserver。无论如何,您正在做什么会引发该错误
  • 是的,我刚刚添加了我用来执行此操作的代码
  • 那么什么时候抛出错误?
  • 当我使用 authns 变量时,它会在 for each 循环中抛出
  • 你能做一个完整的 $jsonData 的 var_dump 并将其发布到一个 pastebin 中吗?

标签: php arrays json laravel


【解决方案1】:

您正在循环通过authns,而它本身就是一个对象。因此,您想要的 nameserver 实际上是第一次迭代中的 $authns

$jsonData-&gt;authns-&gt;nameserver一样访问它

自己试试这个

foreach($jsonData->authns as $authns)
{
    echo $authns;
}

【讨论】:

    【解决方案2】:

    您需要使用关联数组解码 json 对象。

    这是一个例子:

    $data = json_decode(file_get_contents('http://api.domain.com/call'), true);
    

    $data 现在是一个关联数组。

    【讨论】:

    • 他没有将'true'参数发送给json_decode();这就是为什么他不能访问数组中的元素。
    • 现在我看到“Illegal string offset 'nameserver'”,代码是“ "
    • 做一个 print_r($data);以便您了解数组的结构。
    猜你喜欢
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多