在PHP和file_get_contents()

时间:2017-09-21 14:51:26

标签: php json file-get-contents

好的,我很难过。

我尝试了很多不同的方法,而且我花了好几个小时的时间来搜索我的确切情况,或者我感到疲倦和盲目。

这是使用file_get_contents()从URI中提取的原始json:

{"id":"XXX","name":"Customer1","os":"CentOS Linux 7.3.1611 Core","cpu_type":"Intel(R) Xeon(R) CPU E3-1245 V2 @ 3.40GHz","networking_v4":[{"addr":"xxx.xxx.xxx.xxx","if":"eth0"}],"networking_v6":[{"addr":"xxxx","if":"eth0"},{"addr":"xxxx","if":"eth0"}],"agent_version":0.96,"status":"up","last_update":1505949230,"first_update":1500588943,"notifications_count":8,"ip_whois":{"ip":"xxx.xxx.xxx.xxx","hostname":"xxx","city":"Garwood","region":"New Jersey","country":"US","loc":"xxx","org":"AS20473 Choopa, LLC","postal":"xxx"},"additional_fields":[{"value":"xxx","key":"Datacenter"},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""}]}

正如您所看到的,它是一个非常简单的请求,除了嵌套在networking_v4和networking_v6中的数据之外,我还拥有所有数据。

我试图访问这样的人:

'ipv4' => $json->networking_v4->addr,
'ipv4dev' => $json->networking_v4->if,
'ipv6' => $json->networking_v6->addr,
'ipv6dev' => $json->networking_v6->if,

以下是代码的完整快照:

  $content = file_get_contents($url);
  $json = json_decode($content);
  $server_lastupd = $json->last_update;
  $server_firstupd = $json->first_update;
  $server = array(
    'id' => $json->id,
    'name' => $json->name,
    'os' => $json->os,
    'cputype' => $json->cpu_type,
    'ipv4' => $json->networking_v4->addr,
    'ipv4dev' => $json->networking_v4->if,
    'ipv6' => $json->networking_v6->addr,
    'ipv6dev' => $json->networking_v6->if,
    'status' => $json->status,
    'lastupd' => $json->$server_lastupd,
    'firstupd' => $json->$server_firstupd,
    'notifications' => $json->notifications_count,
    'ip' => $json->ip_whois->ip,
    'hostname' => $json->ip_whois->hostname,
    'city' => $json->ip_whois->city,
    'region' => $json->ip_whois->region,
    'country' => $json->ip_whois->country,
    'loc' => $json->ip_whois->loc,
    'org' => $json->ip_whois->org,
    'postal' => $json->ip_whois->postal,
    'dctag' => $json->additonal_fields->dctag,
    'source' => "XXX"
  );
  return $server;

所以我的问题是我似乎无法访问networking_v4和networking_v6中的子内容。

任何有关这方面的帮助都会受到高度赞赏,它让我在昨晚6小时的最佳时间里难以接受,今天还有几个,所以我放弃了,有人请告诉我光明! 非常感谢:))

2 个答案:

答案 0 :(得分:1)

看起来这些嵌套在数组中,来自[{"键':"值"},{"键":"值&# 34;}]方括号。你试过吗

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>

<div id="app">
  <input v-model.number="quantity" type="number">
  <button :disabled="isDisabled">Foo</button>
</div>

答案 1 :(得分:0)

尝试$json->networking_v4[0]->addr

networking_v4networking_v6键都指向数组,因此您需要选择要查看的索引。前者只有一个元素,所以很容易选择索引0,但后者有多个元素,所以你需要找出你想要的那个。