PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How to get object json in php foreach with if-else statement?

 May 16, 2022     file-get-contents, foreach, if-statement, json, php     No comments   

Issue

i want to setup image but got error in line 8

<?php
$url = "https://dog.ceo/api/breeds/image/random";
$json = file_get_content($url);
$obj = json_decode($json, TRUE);

foreach($obj as $key) if
(
echo <img src='$key['message']'/>

else

echo <img src='not_found.png'/>
);
?>

what's the solution?


Solution

You don't need a foreach loop as the api returns regular json. Perhaps you wanted to get such a result.

$url = "https://dog.ceo/api/breeds/image/random";
$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://dog.ceo/api/breeds/image/random',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response, TRUE); 
 if(!empty($response['message'])){
     echo "<img src='{$response['message']}'/>";
 }else{
     echo "<img src='not_found.png'/>";
 }


Answered By - Harvey Dent
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing