简体   繁体   中英

Trying to get property of non-object when get value in variable

trying to get property of non-object in E:\\xampp\\htdocs\\sufiapiwork\\poetlist.php on line 24

Can you fix it? I don't have any idea what happened. Here is my code.

function get_data($url)
{
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$url="someurl";
$data = json_decode(get_data($url), true);

foreach($data as $val)
{
    echo $val->Name_Hi;
}

json_decode($result, true); make associative array / hash instead of anonymous object. The notation is then $val['Name_Hi'] to access the property.

Actually, you would need to firstly specify $data['Result'] index in your array and then use $val['Name_Hi'] to view the data.

foreach($data['Result'] as $val) {

    if($val['Name_Hi'] !== ''){

     echo $val['Name_Hi'] . '<br>';
  }

}

Output:

आजिज़
आज़ाद
अब्दुल्ला हाशिमी
अली रहमती
अमानुल्ला
असदुल्ला शाह
फ़कीरा
फ़ज़ल बिन मुहम्मद अमीन
घासीराम
ग़रीब शाह
गुलामनबी हैदराबादी
ग़वासी दकनी
हसनअली शाह
हातिम दकनी
हुसेनी
इब्न निशाती
इसहाक़ बीजापुरी
Jagjeevan Saheb
करीमुद्दीन सरमस्त
महकम दकनी
महमूद दकनी

The value you are getting from json_decode is an array so you have to use $val['Name_Hi'] .

If you want an object, you have to remove the second parameter from json_decode .


From the doc

The function json_decode() has 4 parameters

  • $json => the json string to decode
  • $assoc = false => if true, you will get an array, if false (or not defines) you will get an object
  • $depth = 512 => sets the maximum depth for decoding nested values
  • $options = 0 => additionnal options for the decode function

The only needed parameter is $json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM