简体   繁体   中英

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:

在此处输入图片说明

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!

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.

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