2016-10-26 27 views
1

Die URL zu JSON StrukturParsing json Daten auf Objekte in PHP

http://api.giphy.com/v1/gifs/search?q=funny+cat&offset=100&limit=1&api_key=dc6zaTOxFJmzC

Jetzt versuche ich diese Json Daten auf meine Objekte zu analysieren:

das ist meine Klasse:

<?php 
class MappedEntity{ 
    private $id; 
    private $mp4Url;  


    public function setId($id){ 
     $this->id=$id; 
    } 
    public function setMp4Url($mp4Url){ 
     $this->mp4Url=$mp4Url; 
    } 
    public function getId(){ 
     return $id; 
    } 
    public function getMp4Url(){ 
     return $mp4Url; 
    } 

    function __contruct($jsonData){ 
     foreach($jsonData as $key => $val){ 
      if(property_exists(__CLASS__,$key)){ 
       $this->$key = $val; 
      } 
     } 
    } 
} 
?> 

der cod e, das ist die Klasse aufrufen:

Undefined variable:: id in C:

<?php 

require_once 'mappedEntity.php'; 


    $keyword = $_POST["keyword"]; 


    $url="http://api.giphy.com/v1/gifs/search?q=".$keyword."&offset=100&limit=1&api_key=dc6zaTOxFJmzC"; 



    $json = file_get_contents($url); 
    $file = json_decode($json); 
    $entity = new MappedEntity($file); 
    echo $entity->getId(); 
?> 

Im

Hinweis bekommen ... \ MappedEntity.php on line 14

was folgt in

13 public function getId(){ 
14   return $id; 
15 } 

OK, änderte ich th e Getter-Methoden und Konstruktor, jetzt der Fehler geht

Notice: Undefined variable: id in C:\....\MappedEntity.php on line 14 

Fatal error: Cannot access empty property in C:...\MappedEntity.php on line 14 

Ich gehe davon aus, meine Mapping-Methode innerhalb des Konstruktor ist nicht in Ordnung zu arbeiten?

+0

'$ this- return> id;' – Progrock

+0

1) Ihre api Schlüssel ist in dieser Zeichenfolge. – Farkie

+0

2) Sie rufen '__construct' anstelle von' __construct' an – Farkie

Antwort

3

Sie die $ dieses auf beiden getID und getMp4URL Funktionen fehlen, sollten sie lesen:

public function getId(){ 
    return $this->id; 
} 

und

public function getMp4Url(){ 
    return $this->mp4Url; 
} 
+0

und der Konstruktor? – Progrock

+0

Erstens beheben Sie den Tippfehler im Konstruktor (es sollte __construct sein), Sie müssen den Körper der Methode nicht ändern, es sieht gut aus. –

+0

Mit Ausnahme dieser werden die Daten immer noch nicht korrekt geladen, da der Konstruktorcode auch keine Daten vom richtigen Teil der Struktur erhält – RiggsFolly