用嵌套元素解析json

时间:2017-09-22 06:26:08

标签: php json parsing

不适用于嵌套元素 输出第一级的元素,并且不读取带有数据的嵌套数组,因为可以获取值 - id,title和location?

<?php

function removeBomUtf8($s){
  if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
        return substr($s,3);
    }else{
        return $s;
    }
}

$url = "https://denden000qwerty.000webhostapp.com/opportunities.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);

while ($el_name = current($decoded)) {
 // echo 'total = ' . $el_name->total_items . 'current = ' . $el_name->current_page . 'total = ' . $el_name->total_pages . '<br>' ;
    echo ' id = ' . $el_name->data[0]->id . ' title = ' . $el_name->data.title . ' location = ' . $el_name->data.location . '<br>' ;
  next($decoded);
}
?>

1 个答案:

答案 0 :(得分:2)

$el_name->data[0]->id是正确的

$el_name->data.title不是

你看到了区别吗?

$decoded是根(不需要迭代它) - 你想迭代data个孩子

<?php
foreach($decoded->data as $data)
{
    $id = (string)$data->id;
    $title = (string)$data->title;
    $location = (string)$data->location;


    echo sprintf('id = %s, title = %s, location = %s<br />', $id, $title, $location);
}
相关问题