Mitch Evans
Mitch Evans

Reputation: 101

PHP Curl Post api call foreach loops

I am trying to make an api call to my re sellers panel for my hosting company. I am successfully receiving the results using the following:

<?php
   function getCountries() {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "myApiUrlHere");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, POST);
      $result = curl_exec($ch);
        foreach ($result as $country) {
          echo '<select>'.$country. '</select>';
        }

      curl_close($ch);
    }

?>

This results in a big block of jumbled code that displays the country code and the country name. (Not sure why that is echoing out though.) The problem is within the foreach loop. using:

foreach ($reult as $country) {
 echo '<select>'.$country. '</select>';
}

I receive this error:

Warning: Invalid argument supplied for foreach() in D:\Hosting\11605285\html\assets\functions\hosting-functions.php on line 10

Exactly what I am seeing is in this photo:

enter image description here

So basically, I'm not understanding why the countries are still echoing out like that. And I'm not sure what invalud argument I am supplying, based on http://www.w3schools.com/php/php_looping_for.asp the arrangement of my code is correct for the for each loop. What have I done wrong? Please help!

Upvotes: 0

Views: 846

Answers (1)

Horse SMith
Horse SMith

Reputation: 1035

foreach expects an array, and it gets a boolean.

If you want a string, then set CURLOPT_RETURNTRANSFER, but it can still return false if not successful, so make sure to check for that:

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

You can for example use explode() to split a string into an array of strings, and see the "see also" section in the explode() documentation for similar useful functions.

Upvotes: 1

Related Questions