0

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!

1
  • I am guessing it is because I'm not putting the results into an array, I'm just echoing out so the foreach loop doesn't have anything to "loop" through. But I'm not sure. Commented Oct 28, 2013 at 1:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That is what I was afraid of.... Any links or ideas on how I could get it into an array?
Mitch Evans, did this answer your question?
Ok, that got me the result I (almost) wanted. I am getting the code for each country as opposed to the country name. Any idea?
Should I just make a new question?
I guess you could if you got the answer to your problem here. :p You should try some for yourself though, using the function and documentation I linked to. To print an array: print_r($array);.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.