Utilisation Json

Résolu
Bonjour,

Malgrés de grosse recherche je n'arrive pas à trouver la solution à mon problème, que je vous expose:

J'ai un fichier Json :
{
"Name": "sport",
«Compter»: 14,
"Fréquence": "Toutes les 15 minutes»,
"Version": 4,
"Newdata": true,
"Lastrunstatus": "succès",
"Lastsuccess": "Tue 24 mars 2015 21:57:57 GMT + 0000 (UTC)",
"Thisversionstatus": "succès",
"Nextrun": "Tue 24 mars 2015 22:12:57 GMT + 0000 (UTC)",
"Thisversionrun": "Tue 24 mars 2015 21:57:57 GMT + 0000 (UTC)",
"résultats": {
"Collection1": [
{
"Property1": "Liste des sports"
}
],
"Collection2": [
{
"Property2": {
"Texte": "Accrobranche",
"Href": "http://www.exemple.fr"
}
},
{
"Property2": {
"Texte": "sportif aérobie»,
"Href": "http://www.exemple.fr"
}
},
{
"Property2": {
"Texte": "Aéromodélisme",
"Href": "http://www.exemple.fr"
}
}

]
}
}


Je souhaiterais simplement récupérer les données à l'intérieur mais avec du php, voila le code php :


<?php

$json = file_get_contents("urldemonfichierjson");

$parsed_json = json_decode($json, true);
$titre = $parsed_json->{'collection1'}[0]->{'property1'};
$sport1 = $parsed_json->{'collection2'}[1]->{'property2'};
$sport2 = $parsed_json->{'collection2'}[1]->{'property2'};

echo "$titre nous avons $sport1 et $sport2";

?>


Mais rien ne s'affiche au niveau de mes variables, mon echo ressemble à un texte à trou. De plus comment puis je faire pour pouvoir mettre par exemple l'accrobranche et l'aéromodélisme sachant qu'ils ont tous les 2 le même nom 'property2'

En vous remerciant de vos réponses

4 réponses

  1. Modérateur
    Par exemple :
    <?php
    $file = "source.json";
    if(file_exists($file)){
    
    	$json = file_get_contents($file);
    	$parsed_json = json_decode($json, true);
    	$arr_results = $parsed_json['results'];
    
    	foreach($arr_results as $collection=>$k){
    	echo "<pre><b>**************<br>".$collection."</b><br>**************<br>";
    		foreach($k as $x=>$v){
    			$titre= isset($v['Property1'])?$v['Property1']:NULL;
    			$sport= isset($v['Property2'])?$v['Property2']:NULL;
    			
    			if($titre){
    				echo "<br><u><b>titre</b></u>:";
    				print_r($titre);
    			}
    			if($sport){
    			  foreach($sport as $S){
    				 $text = isset($S['Texte'])?$S['Texte']:'';
    				 $href = isset($S['Href'])?$S['Href']:'';
    				 echo "<br> Sport :".$text."  ---  ".$href;
    				}
    			}
    		
    		}
    		echo "</pre>";
    		
    	}
    }else{
     echo " <br> No File ! ";
    }
    
    


    NB : Pour mon test .. j'ai mis ça dans mon fichier json :


    {
    "Name": "sport",
    "Compter": 14,
    "Frequence": "Toutes les 15 minutes",
    "Version": 4,
    "Newdata": true,
    "Lastrunstatus": "succes",
    "Lastsuccess": "Tue 24 mars 2015 21:57:57 GMT + 0000 (UTC)",
    "Thisversionstatus": "succes",
    "Nextrun": "Tue 24 mars 2015 22:12:57 GMT + 0000 (UTC)",
    "Thisversionrun": "Tue 24 mars 2015 21:57:57 GMT + 0000 (UTC)",
    "results": {
    "Collection1": [
    {
    "Property1": "Liste des sports"
    }
    ],
    "Collection2": [
    {
    "Property2": [{
    "Texte": "Accrobranche",
    "Href": "http://www.exemple.fr"
    }]
    },
    {
    "Property2": [{
    "Texte": "sportif aerobie",
    "Href": "http://www.exemple.fr"
    }]
    },
    {
    "Property2": [{
    "Texte": "Aeromodelisme",
    "Href": "http://www.exemple.fr"
    }]
    }

    ]
    }
    }



    1
    1. Oh parfait, c'est exactement ca, dernière petite question, comment je fais si je souhaite afficher juste la property2 "aeromodelisme" par exemple ? (merci beaucoup de ton aide)
      0
    2. Modérateur
      @thibault8904Ben.. c'est de la manipulation d'array ....

       echo "<pre>";
       $collection2 = $arr_results['Collection2'];
       $Troisieme_property2 = $collection2[2]['Property2'];
       $texte = $Troisieme_property2[0]['Texte'];
        print_r($texte);
       echo "</pre>";
      

      Qui peut donc s'écrire en une seule fois :
       echo "<pre>";
       $texte= $arr_results['Collection2'][2]['Property2'][0]['Texte'];
       print_r($texte);
       echo "</pre>";
      
      0
    3. Je débute en php et en Json, raison pour laquelle je suis un peu hasardeux dans mes propos x) par exemple là mon probleme c'est de réussir à intégrer l'url de mon fichier json dans cette ligne:
      $file = "source.json";
      "no file" x) meme en faisant
      $file= file_get_content("monurl"); 
      j'ai No file qui apparait..
      0
    4. Modérateur
      @thibault8904$file représente ton fichier ( son chemin )
      dans ton cas ..ça serait
      $file = "monurl";
      
      0
    5. Idem, "No url"..
      0
  2. Modérateur
    Bonjour,
    Visiblement tu as oublié un niveau...
    tes collections sont dans : "résultats"

    A la limite... fais des print_r de tes variables pour voir ce qu'elles contiennent...
    Commence par :
    print_r($parsed_json);

    0
    1. Merci de ta réponse,
      rien n'y fait, j'ai ajouté résultats mais idem.
      print_r($parsed_json); // me renvoi mon fichier Json
      print_r($titre); // me renvoi rien
      print_r($sport1); // me renvoi rien
      print_r($sport2); //me renvoi rien
      0
    2. Modérateur
      @thibault8904
      print_r($parsed_json); // me renvoi mon fichier Json

      Pas tout à fait de la même manière.. mais sous forme d'array...

      peux tu nous coller le résultat de la commande suivante:
      <?php
      
      $json = file_get_contents("urldemonfichierjson");
      
      $parsed_json = json_decode($json, true);
      echo "<pre>";
      print_r($parsed_json);
      echo "</pre>.";
      
      0
    3. ah exact, Voila le résultat:

      Array
      (
      [name] => sport
      [count] => 14
      [frequency] => Every 15 mins
      [version] => 13
      [newdata] => 1
      [lastrunstatus] => success
      [lastsuccess] => Wed Mar 25 2015 00:18:36 GMT+0000 (UTC)
      [thisversionstatus] => success
      [nextrun] => Wed Mar 25 2015 00:33:36 GMT+0000 (UTC)
      [thisversionrun] => Wed Mar 25 2015 00:18:36 GMT+0000 (UTC)
      [results] => Array
      (
      [collection1] => Array
      (
      [0] => Array
      (
      [property1] => Liste des sports
      )

      )

      [collection2] => Array
      (
      [0] => Array
      (
      [property2] => Array
      (
      [text] => Accrobranche
      [href] => http://www.exemple.fr
      )

      )

      [1] => Array
      (
      [property2] => Array
      (
      [text] => Aerobic sportive
      [href] => http://www.exemple.fr
      )

      )

      [2] => Array
      (
      [property2] => Array
      (
      [text] => Aéromodélisme
      [href] => http://www.exemple.fr
      )

      )

      [3] => Array
      (
      [property2] => Array
      (
      [text] => Aérostation
      [href] => http://www.exemple.fr
      )

      )

      [4] => Array
      (
      [property2] => Array
      (
      [text] => Agility
      [href] => http://www.exemple.fr
      )

      )

      [5] => Array
      (
      [property2] => Array
      (
      [text] => Aikido
      [href] => http://www.exemple.fr
      )

      )

      [6] => Array
      (
      [property2] => Array
      (
      [text] => Alpinisme
      [href] => http://www.exemple.fr
      )

      )

      [7] => Array
      (
      [property2] => Array
      (
      [text] => Apnée
      [href] => http://www.exemple.fr
      )

      )

      [8] => Array
      (
      [property2] => Array
      (
      [text] => Aqua gym
      [href] => http://www.exemple.fr
      )

      )

      [9] => Array
      (
      [property2] => Array
      (
      [text] => Arts martiaux artistiques
      [href] => http://www.exemple.fr
      )

      )

      [10] => Array
      (
      [property2] => Array
      (
      [text] => Athlétisme
      [href] => http://www.exemple.fr
      )

      )

      [11] => Array
      (
      [property2] => Array
      (
      [text] => Aviation
      [href] => http://www.exemple.fr
      )

      )

      [12] => Array
      (
      [property2] => Array
      (
      [text] => Aviron
      [href] => http://www.exemple.fr
      )

      )

      )

      )

      )
      .
      0
  3. Up ?
    0
    1. Modérateur
      Ah désolé.
      Je pensais que tu avais compris comment s'en servir...

      Donc... $parsed_json est un ARRAY (comme tu as pu le voir...)
      Tes "conditions" se trouvent dans le sous-tableau results ...
      donc :
      $json = file_get_contents("urldemonfichierjson");
      
      $parsed_json = json_decode($json, true);
      $arr_results = $parsed_json['results'];
      $collection1= $arr_results['collection1'];
      //etc....
      
      
      0
  4. Modérateur
    mais tu peux enlever le if(file_exists...) si ton fichier n'est pas sur ton serveur mais via une URL ...
    $json = file_get_contents('monurl');
    	$parsed_json = json_decode($json, true);
    	$arr_results = $parsed_json['results'];
    
    	foreach($arr_results as $collection=>$k){
    	echo "<pre><b>**************<br>".$collection."</b><br>**************<br>";
    		foreach($k as $x=>$v){
    			$titre= isset($v['Property1'])?$v['Property1']:NULL;
    			$sport= isset($v['Property2'])?$v['Property2']:NULL;
    			
    			if($titre){
    				echo "<br><u><b>titre</b></u>:";
    				print_r($titre);
    			}
    			if($sport){
    			  foreach($sport as $S){
    				 $text = isset($S['Texte'])?$S['Texte']:'';
    				 $href = isset($S['Href'])?$S['Href']:'';
    				 echo "<br> Sport :".$text."  ---  ".$href;
    				}
    			}
    		
    		}
    		echo "</pre>";
    		
    	}
    
    
    0
    1. Ok c'est tout bon, merci de ta patience x)
      0