PHP returning json as string

Asked

Viewed 54 times

-2

I’m returning this one JSON using PHP but the object genre and cast is being returned as string

{  
   "id":"5",
   "title":"A Era do Gelo",
   "year":"2002",
   "age":"0",
   "time":"81",
   "genre":"[{\"id\": 16, \"name\": \"Anima\u00e7\u00e3o\"}, {\"id\": 35, \"name\": \"Com\u00e9dia\"}, {\"id\": 10751, \"name\": \"Fam\u00edlia\"}, {\"id\": 12, \"name\": \"Aventura\"}]",
   "cast":"[{\"name\": \"Ray Romano\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTM4NzA4ODQxNV5BMl5BanBnXkFtZTYwMDA5Mjk1._UY317_CR16,0,214,317_AL_.jpg\", \"imdb_id\": \"nm0005380\", \"character\": \"Manfred       (voice)\"}, {\"name\": \"John Leguizamo\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BNTEyMjMxNDg5NF5BMl5BanBnXkFtZTcwNzczOTY4MQ@@._V1_UY44_CR2,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0000491\", \"character\": \"Sid       (voice)\"}, {\"name\": \"Denis Leary\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTk2MzM4NTA5OV5BMl5BanBnXkFtZTcwMTAxNjA3Mg@@._UY317_CR16,0,214,317_AL_.jpg\", \"imdb_id\": \"nm0001459\", \"character\": \"Diego       (voice)\"}, {\"name\": \"Goran Visnjic\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BNDk1ODI0Nzc0NF5BMl5BanBnXkFtZTcwMzQzNDczNw@@._UY317_CR16,0,214,317_AL_.jpg\", \"imdb_id\": \"nm0899681\", \"character\": \"Soto       (voice)\"}, {\"name\": \"Jack Black\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMjE2MjI4NTQxN15BMl5BanBnXkFtZTgwMDMyMDg4NTE@._V1_UY44_CR1,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0085312\", \"character\": \"Zeke       (voice)\"}, {\"name\": \"Cedric the Entertainer\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTcxODQ1NTU5NV5BMl5BanBnXkFtZTcwNjMwMjY0NA@@._V1_UY44_CR0,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0147825\", \"character\": \"Carl       (voice)\"}, {\"name\": \"Stephen Root\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTQ3MDA3OTA5OF5BMl5BanBnXkFtZTcwMjQ4MDU0NA@@._UY317_CR16,0,214,317_AL_.jpg\", \"imdb_id\": \"nm0740535\", \"character\": \"Frank \/              Start       (voice)\"}, {\"name\": \"Diedrich Bader\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTkzMTkyNzYyOV5BMl5BanBnXkFtZTYwNTMyNDE0._V1_UY44_CR0,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0046033\", \"character\": \"Oscar       (voice)\"}, {\"name\": \"Alan Tudyk\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMjE0MzEwNDUxNV5BMl5BanBnXkFtZTcwNTE1MDAzOQ@@._UY317_CR16,0,214,317_AL_.jpg\", \"imdb_id\": \"nm0876138\", \"character\": \"Lenny \/              Oscar \/              Dab       (voice)\"}, {\"name\": \"Lorri Bagley\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTc1OTAyODk1Nl5BMl5BanBnXkFtZTYwMjM2MDQz._UY317_CR16,0,214,317_AL_.jpg\", \"imdb_id\": \"nm0046715\", \"character\": \"Jennifer       (voice)\"}, {\"name\": \"Jane Krakowski\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMjIyMTQ5NTI1Ml5BMl5BanBnXkFtZTgwNTU2MDY2NzE@._V1_UY44_CR6,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0005105\", \"character\": \"Rachel       (voice)\"}, {\"name\": \"Peter Ackerman\", \"image\": \"\", \"imdb_id\": \"nm0010004\", \"character\": \"Dodo \/              Macrauchenia       (voice)\"}, {\"name\": \"P.J. Benjamin\", \"image\": \"\", \"imdb_id\": \"nm0071344\", \"character\": \"Dodo       (voice)\"}, {\"name\": \"Josh Hamilton\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTU1ODA3MzE1MV5BMl5BanBnXkFtZTcwODMxMzg1MQ@@._V1_UY44_CR0,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0357979\", \"character\": \"Dodo \/              Aardvark       (voice)\"}, {\"name\": \"Chris Wedge\", \"image\": \"https:\/\/images-na.ssl-images-amazon.com\/images\/M\/MV5BMTQ3OTE5MjcxNV5BMl5BanBnXkFtZTgwMTE0MTU0MjE@._V1_UY44_CR0,0,32,44_AL_.jpg\", \"imdb_id\": \"nm0917188\", \"character\": \"Dodo \/              Scrat       (voice)\"}]",
   "director":"Pessoa",
   "description":"O mamute Manny (Ray Romano\/Diogo Vilela), o tigre de dente de sabre Diego (Dennis Leary\/M\u00e1rcio Garcia) e a pregui\u00e7a-gigante Sid (John Leguizamo\/Tadeu Melo) s\u00e3o amigos em uma \u00e9poca muito distante dos dias atuais e vivem suas vidas em meio a muito gelo. At\u00e9 o dia em que eles encontram um menino esquim\u00f3 totalmente sozinho, longe de seus pais, e decidem que precisam ajud\u00e1-lo a achar a sua fam\u00edlia. Enquanto isso, o esquilo pr\u00e9-hist\u00f3rico Scrat segue na sua saga para manter sua amada noz protegida de outros predadores.",
   "source":"http:filme..mll",
   "principalThumb":"\/thumbs\/87be74a3ae83a909d9a54ad354307cfc6566162.jpg",
   "type":"movie",
   "token":"d34c-4638-de1a-bc19-066b-5630-8699-d4c5-9d98-35bc"
}

PHP code:

  function showContents($tb, $token = 0){
    // Busca um conteudo no bd de acordo com o token
    if ($token) {
        $showContents = $this->pdo->connect()->prepare("SELECT * FROM $tb WHERE token=:token");
        $showContents->bindParam(":token", $token, PDO::PARAM_STR);
        $showContents->execute();
        if ($showContents->rowCount() == 1){
            return $showContents->fetchObject();
        }else{
            return false;
        }

    }else{
        // Busca todos os conteudos da tabela no bd
        $showContents = $this->pdo->connect()->query("SELECT * FROM $tb");
        return $showContents->fetchAll(PDO::FETCH_OBJ);
    }

}

My table

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

  • what is the code that this generating that?

  • I edited the question

  • Genre and Cast is also a JSON, it seems. It is not enough to use json_decode to make it an array?

  • The way it’s being shown, I can’t display the data with javascript

  • Because of the quotation marks?

  • Yes............

  • For me, the images are locked where I am, but I replied, I believe they are strings in the BD, so they come to you as a string, not an array of objects.

Show 2 more comments

1 answer

0

They are returning as strings because in the Database I believe they are strings, and the function fetchObject/fetchAll do not automatically convert column to object (not that I know rs).

You have 2 options, do the conversion after fetchObject, or use a class that the constructor does it transparently for you.

Option 1 - After fetchObject

function showContents($tb, $token = 0) {
  // Busca um conteudo no bd de acordo com o token
  if ($token) {
    $showContents = $this->pdo->connect()->prepare("SELECT * FROM $tb WHERE token=:token");
    $showContents->bindParam(":token", $token, PDO::PARAM_STR);
    $showContents->execute();
    if ($showContents->rowCount() == 1) {
      $obj = $showContents->fetchObject();
      $obj->genre = json_decode($obj->genre);
      $obj->cast  = json_decode($obj->cast );
      return $obj;
    } else {
      return false;
    }
  } else {
    // Busca todos os conteudos da tabela no bd
    $showContents = $this->pdo->connect()->query("SELECT * FROM $tb");
    $objs = $showContents->fetchAll(PDO::FETCH_OBJ);
    foreach($objs as &$obj) {
      $obj = $showContents->fetchObject();
      $obj->genre = json_decode($obj->genre);
      $obj->cast  = json_decode($obj->cast );
    }
    unset($obj);
    return $objs;
  }
}

Option 2 - Using a class

class Filme {
  public $id;
  public $title;
  public $year;
  public $age;
  public $time;
  public $genre;
  public $cast;
  public $director;
  public $description;
  public $source;
  public $principalThumb;
  public $type;
  public $token;

  // construtor é chamado depois das propriedades serem preenchidas pelo fetchObject e fetchAll, por isso funciona
  function __construct() {
     $this->genre = json_decode($this->genre);
     $this->cast  = json_decode($this->cast );
  }

}

function showContents($tb, $token = 0, $class_name = "stdClass") {
  // Busca um conteudo no bd de acordo com o token
  if ($token) {
    $showContents = $this->pdo->connect()->prepare("SELECT * FROM $tb WHERE token=:token");
    $showContents->bindParam(":token", $token, PDO::PARAM_STR);
    $showContents->execute();
    if ($showContents->rowCount() == 1) {
      $obj = $showContents->fetchObject($class_name);
      return $obj;
    } else {
      return false;
    }
  } else {
    // Busca todos os conteudos da tabela no bd
    $showContents = $this->pdo->connect()->query("SELECT * FROM $tb");
    $objs = $showContents->fetchAll(PDO::FETCH_OBJ, $class_name);
    unset($obj);
    return $objs;
  }
}

// e na hora de chamar a função, passe o nome da classe
$filme10 = showContents('TBL_FILMES', 10, 'Filme');

More information

Browser other questions tagged

You are not signed in. Login or sign up in order to post.