0

I am trying to get image tags from Imagga image recognition (artificial intelligence service, new V2 version) using cURL and PHP.

I managed to get valid responce, cURL body responce looks like this:

{
"result":{
    "tags":[
        {"confidence":100,"tag":{"en":"pink"}},
        {"confidence":92.6405181884766,"tag":{"en":"petal"}},
        {"confidence":69.8676071166992,"tag":{"en":"flower"}},
        {"confidence":54.1640663146973,"tag":{"en":"bloom"}}
        ]
        }
,"status":{"text":"","type":"success"}
}

I tried to foreach tags, but I am having trouble.

 $response = curl_exec($curl);

 $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
 $body = substr($response, $header_size);
 $header = substr($response, 0, $header_size);
 $rows = explode("\n", $header);

 $err = curl_error($curl);

 curl_close($curl);
 $resp = json_decode( $body, true );

 if ($err) {echo $err; } else {
     // foreach thought tags, and if tag confidence is above 60, than echo it, do something with it...
 }

How to echo some tag if tag confidence is above 60?

Loek
  • 4,037
  • 19
  • 35
Advanced SEO
  • 387
  • 1
  • 4
  • 18
  • Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – Loek Nov 19 '18 at 12:38

1 Answers1

1

just use foreach

<?php
$body = '{
"result":{
    "tags":[
        {"confidence":100,"tag":{"en":"pink"}},
        {"confidence":92.6405181884766,"tag":{"en":"petal"}},
        {"confidence":69.8676071166992,"tag":{"en":"flower"}},
        {"confidence":54.1640663146973,"tag":{"en":"bloom"}}
        ]
        }
,"status":{"text":"","type":"success"}
}';


$resp = json_decode( $body, true );

foreach ($resp['result']['tags'] ?? $tags as $tag) {
    if (
        ($confidence = $tag['confidence'] ?? null) 
        && $confidence >= 60 
        && ($tagName = $tag['tag']['en'] ?? null)
    ) {
        echo $tagName . "\r\n";
    }
}
myxaxa
  • 1,391
  • 1
  • 8
  • 7
  • var_dump($tag) shows array like this: array(2) { ["confidence"]=> float(100) ["tag"]=> array(1) { ["en"]=> string(5) "pink" } } How to echo just tag name "pink"? Could you please update your answer to echo just tag name, if confidence is above 60? – Advanced SEO Nov 19 '18 at 15:44
  • 1
    done. but you should look on http://php.net/manual/en/control-structures.foreach.php and http://php.net/manual/en/language.types.array.php ^_^ – myxaxa Nov 19 '18 at 16:20
  • 1
    Thank you for your answer, it is working fine, also thank you for more info. – Advanced SEO Nov 19 '18 at 17:04
  • np problem at all ^_^ – myxaxa Nov 20 '18 at 09:36