1

i have a php page that gives me a json like this:

{
    "Readings": [
        {
            "MONE_ID": "6",
            "HOTEL_ID": "2",
            "READING_NAME": "head",
            "CURRENT_READING": null,
            "LAST_READING": "12234"
        },
        {
            "MONE_ID": "7",
            "HOTEL_ID": "2",
            "READING_NAME": "ginun",
            "CURRENT_READING": null,
            "LAST_READING": "5444"
        },
        {
            "MONE_ID": "8",
            "HOTEL_ID": "2",
            "READING_NAME": "fire",
            "CURRENT_READING": null,
            "LAST_READING": "6567"
        }
    ]
}

i want to make a post from other php file to get that json and i want to decode it, but i can't understand why its not going well.

<?php 

$postdata = http_build_query(
    array(
        'HOTEL_ID' => '2'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$json = file_get_contents('http://www.hotelsmaintenanceservices.com/getDailyReadings.php', false, $context);

$parsed_json = json_decode($json,true);

foreach ($parsed_json ['Readings'] as $reading) 
    {
            $mone_id=$reading['MONE_ID'];
            echo $mone_id; 
        }
?>

can someone tell me whats wrong?

  • 1
    `var_dump($parsed_json)`, see what really came through. – Marc B May 28 '15 at 17:05
  • it gives me NULL. but if i am doing var_dump($json) it gives me: string(313) "{"Readings":[{"MONE_ID":"6","HOTEL_ID":"2","READING_NAME":"head","CURRENT_READING":null,"LAST_READING":"12234"},{"MONE_ID":"7","HOTEL_ID":"2","READING_NAME":"ginun","CURRENT_READING":null,"LAST_READING":"5444"},{"MONE_ID":"8","HOTEL_ID":"2","READING_NAME":"fire","CURRENT_READING":null,"LAST_READING":"6567"}]}" – gamliel basha May 28 '15 at 17:22
  • your json is corrupt. `` at the start is NOT json and will cause the entire decode to fail. – Marc B May 28 '15 at 17:24
  • why its giving me this " – gamliel basha May 28 '15 at 17:25
  • you'd have to ask this hotelsmaintenanceservices.com why they're dumping out in valid json. – Marc B May 28 '15 at 17:25
  • I have found the problem, the PHP file was saved in UTF format instead of ASCII – gamliel basha May 28 '15 at 19:03
  • You should save it using UTF-8 without BOM. Please check this for more information about UTF files https://stackoverflow.com/questions/2223882/whats-different-between-utf-8-and-utf-8-without-bom – Michal Przybylowicz May 29 '15 at 06:02

0 Answers0