Partage
  • Partager sur Facebook
  • Partager sur Twitter

Afficher des données API en PHP

    21 septembre 2022 à 19:46:46

    Bonjour,
    Moi c'est Ludovic j'ai 28 ans.
    Débutant en PHP, j'essaie de m'intéresser à la manipulation d'API.
    J'essaie d'afficher les données d'une API mais ... je n'y arrive pas (évidemment)
    Je viens évidemment sur le forum pour avoir de l'aide (évidemment avant j'ai essayé de parcourir les sites pour essayer de trouver des infos pour me dépatouiller).

    J'ai construit mon code de la façon suivante :
    J'ai mis un script cURL en début de fichier (script qui fonctionne puisque j'ai bien les datas brutes de l'API qui s'affichent avec l'echo du $response. Mon problème c'est pour les afficher)
    Voici les données affichées par le $response
    {
    "page": 1,
    "results": [
    {
    "adult": false,
    "backdrop_path": "/yrdAamkeqXHm0UYukk8xgoCvc7G.jpg",
    "genre_ids": [
    12,
    28,
    878
    ],
    "id": 11,
    "original_language": "en",
    "original_title": "Star Wars",
    "overview": "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to rescue the beautiful princess and restore peace and justice in the Empire.",
    "popularity": 73.589,
    "poster_path": "/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg",
    "release_date": "1977-05-25",
    "title": "Star Wars",
    "video": false,
    "vote_average": 8.2,
    "vote_count": 17698
    },
    {
    "adult": false,
    "backdrop_path": "/vV5knD9jlW8QaOhCgf4129hbIIh.jpg",
    "genre_ids": [
    10751,
    16,
    35,
    878
    ],
    "id": 980804,
    "original_language": "en",
    "original_title": "LEGO Star Wars Summer Vacation",
    "overview": "Looking for a much-needed break, Finn arranges a surprise vacation for his friends Rey, Poe, Rose, Chewie, BB-8, R2-D2, and C-3PO, aboard the luxurious Halcyon. However, Finn's plan to have one last hurrah together quickly goes awry.",
    "popularity": 139.165,
    "poster_path": "/2SatEFCs04oFRqkZuY1fODYXeFI.jpg",
    "release_date": "2022-08-05",
    "title": "LEGO Star Wars Summer Vacation",
    "video": false,
    "vote_average": 5.8,
    "vote_count": 30
    },
    {
    "adult": false,
    "backdrop_path": "/8BTsTfln4jlQrLXUBquXJ0ASQy9.jpg",
    "genre_ids": [
    12,
    28,
    878,
    14
    ],
    "id": 140607,
    "original_language": "en",
    "original_title": "Star Wars: The Force Awakens",
    "overview": "Thirty years after defeating the Galactic Empire, Han Solo and his allies face a new threat from the evil Kylo Ren and his army of Stormtroopers.",
    "popularity": 65.197,
    "poster_path": "/wqnLdwVXoBjKibFRR5U3y0aDUhs.jpg",
    "release_date": "2015-12-15",
    "title": "Star Wars: The Force Awakens",
    "video": false,
    "vote_average": 7.3,
    "vote_count": 17334
    },
    {
    "adult": false,
    "backdrop_path": "/5Iw7zQTHVRBOYpA0V6z0yypOPZh.jpg",
    "genre_ids": [
    12,
    28,
    878
    ],
    "id": 181808,
    "original_language": "en",
    "original_title": "Star Wars: The Last Jedi",
    "overview": "Rey develops her newly discovered abilities with the guidance of Luke Skywalker, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.",
    "popularity": 60.349,
    "poster_path": "/ySaaKHOLAQU5HoZqWmzDIj1VvZ1.jpg",
    "release_date": "2017-12-13",
    "title": "Star Wars: The Last Jedi",
    "video": false,
    "vote_average": 6.9,
    "vote_count": 13337
    },
    {
    "adult": false,
    "backdrop_path": "/f53Jujiap580mgfefID0T0g2e17.jpg",
    "genre_ids": [
    16,
    10751,
    878,
    35
    ],
    "id": 857702,
    "original_language": "en",
    "original_title": "LEGO Star Wars Terrifying Tales",
    "overview": "Poe Dameron and BB-8 must face the greedy crime boss Graballa the Hutt, who has purchased Darth Vader’s castle and is renovating it into the galaxy’s first all-inclusive Sith-inspired luxury hotel.",
    "popularity": 67.226,
    "poster_path": "/fYiaBZDjyXjvlY6EDZMAxIhBO1I.jpg",
    "release_date": "2021-10-01",
    "title": "LEGO Star Wars Terrifying Tales",
    "video": false,
    "vote_average": 6.8,
    "vote_count": 197
    },
    {
    "adult": false,
    "backdrop_path": "/SPkEiZGxq5aHWQ2Zw7AITwSEo2.jpg",
    "genre_ids": [
    12,
    28,
    878
    ],
    "id": 181812,
    "original_language": "en",
    "original_title": "Star Wars: The Rise of Skywalker",
    "overview": "The surviving Resistance faces the First Order once again as the journey of Rey, Finn and Poe Dameron continues. With the power and knowledge of generations behind them, the final battle begins.",
    "popularity": 58.345,
    "poster_path": "/db32LaOibwEliAmSL2jjDF6oDdj.jpg",
    "release_date": "2019-12-18",
    "title": "Star Wars: The Rise of Skywalker",
    "video": false,
    "vote_average": 6.4,
    "vote_count": 8067
    },
    {
    "adult": false,
    "backdrop_path": "/ojHCeDULAkQK25700fhRU75Tur2.jpg",
    "genre_ids": [
    878,
    12,
    28
    ],
    "id": 348350,
    "original_language": "en",
    "original_title": "Solo: A Star Wars Story",
    "overview": "Through a series of daring escapades deep within a dark and dangerous criminal underworld, Han Solo meets his mighty future copilot Chewbacca and encounters the notorious gambler Lando Calrissian.",
    "popularity": 38.081,
    "poster_path": "/3IGbjc5ZC5yxim5W0sFING2kdcz.jpg",
    "release_date": "2018-05-15",
    "title": "Solo: A Star Wars Story",
    "video": false,
    "vote_average": 6.6,
    "vote_count": 7278
    },
    {
    "adult": false,
    "backdrop_path": "/6t8ES1d12OzWyCGxBeDYLHoaDrT.jpg",
    "genre_ids": [
    28,
    12,
    878
    ],
    "id": 330459,
    "original_language": "en",
    "original_title": "Rogue One: A Star Wars Story",
    "overview": "A rogue band of resistance fighters unite for a mission to steal the Death Star plans and bring a new hope to the galaxy.",
    "popularity": 44.208,
    "poster_path": "/i0yw1mFbB7sNGHCs7EXZPzFkdA1.jpg",
    "release_date": "2016-12-14",
    "title": "Rogue One: A Star Wars Story",
    "video": false,
    "vote_average": 7.5,
    "vote_count": 13446
    },
    {
    "adult": false,
    "backdrop_path": "/xEdnGUc8KeZ7h0eEgSN3ERhjgL0.jpg",
    "genre_ids": [
    16,
    28,
    878,
    12
    ],
    "id": 12180,
    "original_language": "en",
    "original_title": "Star Wars: The Clone Wars",
    "overview": "Set between Episode II and III, The Clone Wars is the first computer animated Star Wars film. Anakin and Obi Wan must find out who kidnapped Jabba the Hutt's son and return him safely. The Seperatists will try anything to stop them and ruin any chance of a diplomatic agreement between the Hutts and the Republic.",
    "popularity": 27.506,
    "poster_path": "/ywRtBu88SLAkNxD0GFib6qsFkBK.jpg",
    "release_date": "2008-08-05",
    "title": "Star Wars: The Clone Wars",
    "video": false,
    "vote_average": 6.1,
    "vote_count": 1641
    },
    {
    "adult": false,
    "backdrop_path": "/5fu7fzy4NZTsL1Jap00UBIInAuB.jpg",
    "genre_ids": [
    12,
    28,
    878
    ],
    "id": 1893,
    "original_language": "en",
    "original_title": "Star Wars: Episode I - The Phantom Menace",
    "overview": "Anakin Skywalker, a young slave strong with the Force, is discovered on Tatooine. Meanwhile, the evil Sith have returned, enacting their plot for revenge against the Jedi.",
    "popularity": 34.236,
    "poster_path": "/6wkfovpn7Eq8dYNKaG5PY3q2oq6.jpg",
    "release_date": "1999-05-19",
    "title": "Star Wars: Episode I - The Phantom Menace",
    "video": false,
    "vote_average": 6.5,
    "vote_count": 12531
    },
    {
    "adult": false,
    "backdrop_path": "/2UEKQtkx35hGCkgfA5lPVu7GaAm.jpg",
    "genre_ids": [
    16,
    878,
    12
    ],
    "id": 782054,
    "original_language": "ja",
    "original_title": "Doraemon: Nobita's Little Star Wars 2021",
    "overview": "One day during summer vacation, a palm-sized alien named Papi appears from a small rocket that Nobita picks up. He is the president of Pirika, a small planet in outer space, and has come to Earth to escape the rebels. Doraemon and his friends are puzzled by Papi’s small size, but as they play together using the secret tool “Small Light”, they gradually become friends. However, a whale-shaped space battleship comes to earth and attacks Doraemon, Nobita and the others in order to capture Papi. Feeling responsible for getting everyone involved, Papi tries to stand up to the rebels. Doraemon and his friends leave for the planet Pirika to protect their dear friend and his home.",
    "popularity": 18.804,
    "poster_path": "/48gKZioIDeUOI0afbYv3kh9u9RQ.jpg",
    "release_date": "2022-03-04",
    "title": "Doraemon: Nobita's Little Star Wars 2021",
    "video": false,
    "vote_average": 5,
    "vote_count": 3
    },
    {
    "adult": false,
    "backdrop_path": "/1Lhc32P0a62BgMFgd20wXR1osR3.jpg",
    "genre_ids": [
    16,
    10751,
    12,
    35,
    878
    ],
    "id": 732670,
    "original_language": "en",
    "original_title": "LEGO Star Wars Holiday Special",
    "overview": "As her friends prep for a Life Day holiday celebration, Rey journeys with BB-8 on a quest to gain a deeper knowledge of the Force at a mysterious Jedi Temple. There, she embarks on a cross-timeline adventure through beloved moments in Star Wars history, coming into contact with iconic heroes and villains from all eras of the saga. But will she make it back in time for the Life Day feast?",
    "popularity": 20.728,
    "poster_path": "/zyzJSI7UZZzz5Toj10rYGF5689z.jpg",
    "release_date": "2020-11-17",
    "title": "LEGO Star Wars Holiday Special",
    "video": false,
    "vote_average": 6.7,
    "vote_count": 248
    },
    {
    "adult": false,
    "backdrop_path": "/rkKx3O4e1tNDDpS3eERWZHumSMm.jpg",
    "genre_ids": [
    12,
    28,
    878
    ],
    "id": 1895,
    "original_language": "en",
    "original_title": "Star Wars: Episode III - Revenge of the Sith",
    "overview": "The evil Darth Sidious enacts his final plan for unlimited power -- and the heroic Jedi Anakin Skywalker must choose a side.",
    "popularity": 36.372,
    "poster_path": "/xfSAoBEm9MNBjmlNcDYLvLSMlnq.jpg",
    "release_date": "2005-05-17",
    "title": "Star Wars: Episode III - Revenge of the Sith",
    "video": false,
    "vote_average": 7.4,
    "vote_count": 11766
    },
    {
    "adult": false,
    "backdrop_path": "/pXnNSeyTCUebjpHTiZt7v6FZId0.jpg",
    "genre_ids": [
    12,
    28,
    878
    ],
    "id": 1894,
    "original_language": "en",
    "original_title": "Star Wars: Episode II - Attack of the Clones",
    "overview": "Following an assassination attempt on Senator Padmé Amidala, Jedi Knights Anakin Skywalker and Obi-Wan Kenobi investigate a mysterious plot that could change the galaxy forever.",
    "popularity": 31.458,
    "poster_path": "/oZNPzxqM2s5DyVWab09NTQScDQt.jpg",
    "release_date": "2002-05-15",
    "title": "Star Wars: Episode II - Attack of the Clones",
    "video": false,
    "vote_average": 6.5,
    "vote_count": 11346
    },
    {
    "adult": false,
    "backdrop_path": "/uNjBnOmdjZoiWTLQ938YJZ1cYVU.jpg",
    "genre_ids": [
    16,
    35,
    10751,
    878,
    12,
    10770
    ],
    "id": 392216,
    "original_language": "en",
    "original_title": "Phineas and Ferb: Star Wars",
    "overview": "Phineas and Ferb become the galaxy's unlikeliest last hope when they must return the Death Star plans to the Rebel Alliance.",
    "popularity": 11.903,
    "poster_path": "/xomphpz7MIasqVluPX83TjoTL8G.jpg",
    "release_date": "2014-07-26",
    "title": "Phineas and Ferb: Star Wars",
    "video": false,
    "vote_average": 7.1,
    "vote_count": 155
    },
    {
    "adult": false,
    "backdrop_path": "/ae9xlnkS2qb5Dy9Mtlu68AWh42O.jpg",
    "genre_ids": [
    12,
    35,
    10751,
    878
    ],
    "id": 74849,
    "original_language": "en",
    "original_title": "The Star Wars Holiday Special",
    "overview": "Luke Skywalker and Han Solo battle evil Imperial forces to help Chewbacca reach his imperiled family on the Wookiee planet - in time for Life Day, their most important day of the year!",
    "popularity": 14.539,
    "poster_path": "/1TY4OAkcHRovlHDxSLW7UDJlild.jpg",
    "release_date": "1978-12-01",
    "title": "The Star Wars Holiday Special",
    "video": false,
    "vote_average": 3.3,
    "vote_count": 370
    },
    {
    "adult": false,
    "backdrop_path": null,
    "genre_ids": [
    35,
    878,
    16
    ],
    "id": 51888,
    "original_language": "en",
    "original_title": "Robot Chicken: Star Wars Episode III",
    "overview": "Robot Chicken: Star Wars Episode III, directed by Chris McKay, combines the satirical sensibilities of Green and Matthew Senreich's Robot Chicken with characters of the Star Wars universe.",
    "popularity": 13.208,
    "poster_path": "/mi2lVho2zpfwcxI6yC1QYJi435D.jpg",
    "release_date": "2010-12-19",
    "title": "Robot Chicken: Star Wars Episode III",
    "video": false,
    "vote_average": 7.4,
    "vote_count": 119
    },
    {
    "adult": false,
    "backdrop_path": null,
    "genre_ids": [
    16,
    35,
    878
    ],
    "id": 42979,
    "original_language": "en",
    "original_title": "Robot Chicken: Star Wars",
    "overview": "A series of 30 sketches, following the hilarious antics of various characters from a galaxy, far, far away.",
    "popularity": 7.401,
    "poster_path": "/h44WN4mVJ6wEpJgLaaNoFjv0NAo.jpg",
    "release_date": "2007-07-17",
    "title": "Robot Chicken: Star Wars",
    "video": false,
    "vote_average": 7.2,
    "vote_count": 206
    },
    {
    "adult": false,
    "backdrop_path": "/c8XIFuJCPTtTJdSRpqnUoMr6eK1.jpg",
    "genre_ids": [
    878
    ],
    "id": 667574,
    "original_language": "en",
    "original_title": "Battle Star Wars",
    "overview": "When the leader of the evil Coalition threatens to destroy a Rebel planet for its resources, his daughter will have no choice but to join the Rebel side and fight for what is right.",
    "popularity": 6.476,
    "poster_path": "/ocA0ECiFoB4d1HITyEDQlLk7x84.jpg",
    "release_date": "2020-01-28",
    "title": "Battle Star Wars",
    "video": false,
    "vote_average": 5.1,
    "vote_count": 33
    },
    {
    "adult": false,
    "backdrop_path": null,
    "genre_ids": [
    99
    ],
    "id": 378386,
    "original_language": "en",
    "original_title": "Star Wars: Greatest Moments",
    "overview": "Alex Zane counts down the top 20 Star Wars moments as voted by the public. Includes contributions from famous fans as well as the stars and crew of the intergalactic saga.",
    "popularity": 6.181,
    "poster_path": "/zIffPwISrW48qSmvAXEV27lBTMA.jpg",
    "release_date": "2015-12-26",
    "title": "Star Wars: Greatest Moments",
    "video": false,
    "vote_average": 6.6,
    "vote_count": 27
    }
    ],
    "total_pages": 7,
    "total_results": 139
    }

    Mon code php (avec un script curl en entête)

    <?php
    $curl = curl_init();
    
    curl_setopt_array($curl, [
    	CURLOPT_URL => "ici l'url de mon API",
    	CURLOPT_RETURNTRANSFER => true,,
    	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    	CURLOPT_CUSTOMREQUEST => "GET",
    ]);
    
    $response = curl_exec($curl);
    $err = curl_error($curl);
    
    curl_close($curl);
    
    if ($err) {
    	echo "cURL Error #:" . $err;
    } else {
    	echo $response."<br />";
    }
    ?>

     Ensuite j'ai fait la construction de ma page (avec le squelette HTML classique) et dans le body j'ai fait le test sur le genre_ids avec un script pour essayer d'afficher des données


    <?php
        $resultat = json_decode($response,true);
            foreach($resultat as $film) {
    	        $id_genre = $film->results->genre_ids;
    		    echo $id_genre;
                   }
    ?>
          

    Donc j'ai des messages d'erreur disant 
    Warning: Attempt to read property "results" on int in [l'adresse de mon site] online 38
    Warning: Attempt to read property "genre_ids" on null in [l'adresse de mon site] online 38
    Warning: Attempt to read property "results" on array in [l'adresse de mon site] online 38

    Evidemment j'ai codé comme un goret (parce que je suis perdu et je ne sais pas comment faire, donc j'ai tâtonné à droite à gauche pour essayer d'obtenir des infos)

    Merci pour l'attention et l'aide que vous me donnerez
    Ludo

    • Partager sur Facebook
    • Partager sur Twitter
      22 septembre 2022 à 14:12:32

      Salut, ta boucle for ne peut pas fonctionner. Essaye de remplacer   $resultat par $resultat->results dans ta boucle for.

      N'hésite pas à faire des var_dump() dans ton code pour comprendre les données qui passent dans tes variables.

      • Partager sur Facebook
      • Partager sur Twitter
        22 septembre 2022 à 20:15:35

        Salut,
        Merci pour ta réponse.
        Si j'ai bien compris ta proposition, j'ai mis $resultat->results dans la boucle foreach (dans la parenthèse).
        Ca ne fonctionne toujours pas.
        Voici les messages d'erreur que j'ai 
        Warning: Attempt to read property "results" on array in [l'adresse de mon site] on line 37

        Warning: foreach() argument must be of type array|object, null given in [l'adresse de mon site] on line 37

        Je l'ai fait en enlevant le results sur la ligne 
        $resultat = json_decode($response,true);
        foreach($resultat->results as $film) {
        $id_genre = $film->genre_ids;
        echo $id_genre;
        }

        le var_dump de $id_genre m'indique Warning: Undefined variable $id_genre in [l'adresse de mon site] on line 41
        NULL

        J'ai remis la ligne 
        $id_genre = $film->results->genre_ids; 

        J'ai exactement les 3 mêmes messages d'erreur

        Ludo

        -
        Edité par NewBi1 22 septembre 2022 à 20:16:00

        • Partager sur Facebook
        • Partager sur Twitter
          23 septembre 2022 à 9:17:37

          Salut,  j'ai testé ton ton exemple et j'ai fait quelques modifications.

          <?php
          
          $response ='{
          "page": 1,
          "results": [
          {
          "adult": false,
          "backdrop_path": "/yrdAamkeqXHm0UYukk8xgoCvc7G.jpg",
          "genre_ids": [
          12,
          28,
          878
          ],
          "id": 11,
          "original_language": "en",
          "original_title": "Star Wars",
          "overview": "Princess Leia is captured and held hostage by the evil Imperial forces in their effort to take over the galactic 
          Empire. Venturesome Luke Skywalker and dashing captain Han Solo team together with the loveable robot duo R2-D2 and C-3PO to 
          rescue the beautiful princess and restore peace and justice in the Empire.",
          "popularity": 73.589,
          "poster_path": "/6FfCtAuVAW8XJjZ7eWeLibRLWTw.jpg",
          "release_date": "1977-05-25",
          "title": "Star Wars",
          "video": false,
          "vote_average": 8.2,
          "vote_count": 17698
          },
          {
          "adult": false,
          "backdrop_path": "/vV5knD9jlW8QaOhCgf4129hbIIh.jpg",
          "genre_ids": [
          10751,
          16,
          35,
          878
          ],
          "id": 980804,
          "original_language": "en",
          "original_title": "LEGO Star Wars Summer Vacation",
          "overview": "Looking for a much-needed break, Finn arranges a surprise vacation for his friends Rey, Poe, Rose, Chewie, BB-8, 
          R2-D2, and C-3PO, aboard the luxurious Halcyon. However, Finns plan to have one last hurrah together quickly goes awry.",
          "popularity": 139.165,
          "poster_path": "/2SatEFCs04oFRqkZuY1fODYXeFI.jpg",
          "release_date": "2022-08-05",
          "title": "LEGO Star Wars Summer Vacation",
          "video": false,
          "vote_average": 5.8,
          "vote_count": 30
          },
          {
          "adult": false,
          "backdrop_path": null,
          "genre_ids": [
          99
          ],
          "id": 378386,
          "original_language": "en",
          "original_title": "Star Wars: Greatest Moments",
          "overview": "Alex Zane counts down the top 20 Star Wars moments as voted by the public. Includes contributions from famous fans 
          as well as the stars and crew of the intergalactic saga.",
          "popularity": 6.181,
          "poster_path": "/zIffPwISrW48qSmvAXEV27lBTMA.jpg",
          "release_date": "2015-12-26",
          "title": "Star Wars: Greatest Moments",
          "video": false,
          "vote_average": 6.6,
          "vote_count": 27
          }
          ],
          "total_pages": 7,
          "total_results": 139
          }';
          
          
          
              $resultat = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response), true );
              foreach($resultat["results"] as $film) {
                          
                  $id_genre = $film["genre_ids"];
                  var_dump( $id_genre);
              }
          

          Tu peux partir de cette base qui fonctionne pour continuer ton développement.

          • Partager sur Facebook
          • Partager sur Twitter
            23 septembre 2022 à 16:02:47

            Bonjour,

            C'est sympa mais chez moi ça ne fonctionne pas 

            ça me retourne l'erreur suivante 

            Warning: Array to string conversion in [l'adresse de mon site] on line 40
            Array

            Pour le moment je développe sous XAMPP est ce que ça peut provenir de la ?
            En tout cas c'est sympa de t'être penché sur mon problème. Merci
            Ludo

            -
            Edité par NewBi1 24 septembre 2022 à 11:28:23

            • Partager sur Facebook
            • Partager sur Twitter
              25 septembre 2022 à 8:44:41

              Bon finalement j'ai réussi a me dépatouiller.
              J'ai fait une recherche sur le message d'erreur que j'avais sur le net et j'ai trouvé une solution qui fonctionne.
              Merci pour ton aide
              Ludo

              PS : juste pour que je sois moins idiot, peux tu m'expliquer ton expression régulière dans le json_decode ?

              Merci

              -
              Edité par NewBi1 25 septembre 2022 à 8:46:33

              • Partager sur Facebook
              • Partager sur Twitter
                26 septembre 2022 à 11:56:23

                Salut, 

                D'accord super !

                J'avais fait cette regex pour enlever les caractères spéciaux dans le json pendant mes tests

                • Partager sur Facebook
                • Partager sur Twitter
                  26 septembre 2022 à 12:39:01

                  Bonjour, ce message d'erreur:

                  Warning: Attempt to read property "results" on array in [l'adresse de mon site] on line 37

                  a l'air d'indiquer que le résultat fournit par json_decode est un tableau et pas un objet bizarre de StdClass

                  <?php
                  
                  $resultat = json_decode($response,true);
                  
                  foreach($resultat["results"] as $film) {
                  	$id_genre = $film["genre_ids"];
                  }

                  La deuxième erreur à l'air d'indiquer que PHP ne peut pas convertir un tableau en chaîne de texte $film["genre_ids"] renvoi un tableau de nombre (les id qui correspondent au genre du film) tu peux l'afficher avec un var_dump je pense:

                  <?php
                  
                  $resultat = json_decode($response, true);
                  
                  foreach($resultat["results"] as $film) {
                  	$id_genre = $film["genre_ids"];
                      
                      echo "<pre>";
                      var_dump($id_genre);
                      echo "<pre>";
                  }




                  -
                  Edité par SamuelGaborieau3 26 septembre 2022 à 12:39:26

                  • Partager sur Facebook
                  • Partager sur Twitter

                  suggestion de présentation.

                    26 septembre 2022 à 19:40:32

                    Merci , c'est bon j'ai résolu mes soucis, ça fonctionne

                    -
                    Edité par NewBi1 27 septembre 2022 à 9:35:22

                    • Partager sur Facebook
                    • Partager sur Twitter
                      28 septembre 2022 à 10:44:53

                      Par contre j'ai un souci (probablement très bête). Dans le 1er exemple, l'API commence par un array result. Lorsqu'il n'y a rien, je n'arrive pas à le coder. J'ai des messages erreurs partout (le problème vient de ma boucle foreach). Voici un exemple de résultat API

                      {
                      "adult": false,
                      "backdrop_path": "/rr7E0NoGKxvbkb89eR1GwfoYjpA.jpg",
                      "belongs_to_collection": null,
                      "budget": 63000000,
                      "genres": [
                      {
                      "id": 18,
                      "name": "Drame"
                      }
                      ],
                      "homepage": "",
                      "id": 550,
                      "imdb_id": "tt0137523",
                      "original_language": "en",
                      "original_title": "Fight Club",
                      "overview": "Le narrateur, sans identité précise, vit seul, travaille seul, dort seul, mange seul ses plateaux‐repas pour une personne comme beaucoup d’autres personnes seules qui connaissent la misère humaine, morale et sexuelle. C’est pourquoi il va devenir membre du Fight club, un lieu clandestin où il va pouvoir retrouver sa virilité, l’échange et la communication. Ce club est dirigé par Tyler Durden, une sorte d’anarchiste entre gourou et philosophe qui prêche l’amour de son prochain.",
                      "popularity": 109.752,
                      "poster_path": "/6NdNO1dq9w54ujk2G4sK4ogsf0H.jpg",
                      "production_companies": [
                      {
                      "id": 508,
                      "logo_path": "/7cxRWzi4LsVm4Utfpr1hfARNurT.png",
                      "name": "Regency Enterprises",
                      "origin_country": "US"
                      },
                      {
                      "id": 711,
                      "logo_path": "/tEiIH5QesdheJmDAqQwvtN60727.png",
                      "name": "Fox 2000 Pictures",
                      "origin_country": "US"
                      },
                      {
                      "id": 4700,
                      "logo_path": "/A32wmjrs9Psf4zw0uaixF0GXfxq.png",
                      "name": "The Linson Company",
                      "origin_country": "US"
                      },
                      {
                      "id": 20555,
                      "logo_path": "/hD8yEGUBlHOcfHYbujp71vD8gZp.png",
                      "name": "Taurus Film",
                      "origin_country": "DE"
                      },
                      {
                      "id": 54051,
                      "logo_path": null,
                      "name": "Atman Entertainment",
                      "origin_country": ""
                      },
                      {
                      "id": 54052,
                      "logo_path": null,
                      "name": "Knickerbocker Films",
                      "origin_country": "US"
                      }
                      ],
                      "production_countries": [
                      {
                      "iso_3166_1": "DE",
                      "name": "Germany"
                      },
                      {
                      "iso_3166_1": "US",
                      "name": "United States of America"
                      }
                      ],
                      "release_date": "1999-10-15",
                      "revenue": 100853753,
                      "runtime": 139,
                      "spoken_languages": [
                      {
                      "english_name": "English",
                      "iso_639_1": "en",
                      "name": "English"
                      }
                      ],
                      "status": "Released",
                      "tagline": "Le chaos. Confusion. Savon.",
                      "title": "Fight Club",
                      "video": false,
                      "vote_average": 8.433,
                      "vote_count": 24851
                      }

                      Lorsque l'API commence par results (comme le tout premier exemple) dans le foreach on utilise le results (je reprends le code envoyé par AC14)

                      $resultat = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response), true );
                          foreach($resultat["results"] as $film) {
                                       
                              $id_genre = $film["genre_ids"];
                              var_dump( $id_genre);
                          }

                      Le foreach prend le results entre crochets. Lorsqu'il n'y a rien je ne sais pas comment le coder (j'ai essayé $resultat[" "] as ... ou $resultat as ...  j'ai même essayé un $resultat{} as ) j'ai des messages d'erreur partout.
                      Merci pour votre éclairage
                      Ludo


                      -
                      Edité par NewBi1 28 septembre 2022 à 13:56:39

                      • Partager sur Facebook
                      • Partager sur Twitter
                        28 septembre 2022 à 13:13:06

                        bonjour, voir la doc des fonctions isset / empty
                        • Partager sur Facebook
                        • Partager sur Twitter

                        yasakani no magatama

                        Afficher des données API en PHP

                        × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                        × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                        • Editeur
                        • Markdown