0

I have a json file data, cache.txt. When I try to write the data I retrieved from it I get this error Illegal string offset for all fields.

I get the data but I cannot read fields, I don't know why

The file Data

s:729:"[{"id":"787","name":"XXY","release":"2007","Language":"Spanish","cover":"upload\/photos\/2019\/06\/sKRTzoEjRPCeHWsCrcHi_19_c12db8f07c6acb75a430a0c63c4f7e8d_image.jpg"},{"id":"638","name":"Barfi","release":"2012","Language":"Hindi","cover":"upload\/photos\/2019\/04\/uJD7t2q3XQcsOjSORv1c_25_eff4e484426302484d8de738dcb99470_image.jpg"},{"id":"937","name":"Secretary","release":"2002","Language":"English","cover":"upload\/photos\/2019\/01\/Secretary.jpg"},{"id":"829","name":"Love Meet Hope","release":"2016","Language":"English","cover":"upload\/photos\/2019\/01\/Love-Meet-Hope.jpg"},{"id":"412","name":"Daughters Of Darkness","release":"1971","Language":"English","cover":"upload\/photos\/2019\/01\/Daughters-Of-Darkness.jpg"}]";


<?php
WritePopularMovies();

function WriteData()
{
   $movies = json_decode(GetData(),true);

   for($i=0;$i < 5;$i++)
   {
        echo "<div class='col-exs-6 col-xs-4 col-sm-3 col-md-3'>";
        echo "<figure>";
        echo "<a href='" . $movies[$i]['id'] . "'>";
        echo "<img src='" . $movies[$i]['cover'] ."' alt='".$movies[$i]['name'] .
             "' class='responsive-img' style='height:250px;width:170px'>";
        echo "</a>";
        echo "<h6 title=". $movies[$i]['name'] ."><a href='". $movies[$i]['id']."'>".
              $movies[$i]['name']."</a></h6>";
        echo "<p>". $movies[$i]['genre']. "(".$movies[$i]['language'].")| ". 
        $movies[$i]['release'] ."</p>";
        echo "</figure>";
        echo "</div>";
   }
}

function GetData() {
   $data  = array();
   $file = $_SERVER['DOCUMENT_ROOT'] .'/cache.txt';
   $data = unserialize(file_get_contents($file));
   return json_encode($data,true);
}
?>

I tried to solve it but with no luck, so I will appreciate your help.

Many thanks

4
  • Why are the data first json encoed and then serialized with PHP's serialize-function? Seems redundant. Commented Dec 21, 2019 at 13:44
  • Don't return json_encode($data,true); but return $data Commented Dec 21, 2019 at 13:45
  • Also, there's no 'genre' in that data. Commented Dec 21, 2019 at 13:47
  • 1
    Also 'language' -> 'Language' Commented Dec 21, 2019 at 13:47

1 Answer 1

1

In your GetData() you are reading the data and then encoding it...

return json_encode($data,true);

this isn't necessary and stops the next part working, just return the raw data

return $data;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.