简体   繁体   English

PHP Curl Post API调用foreach循环

[英]PHP Curl Post api call foreach loops

I am trying to make an api call to my re sellers panel for my hosting company. 我正在尝试通过API致电托管公司的“我的卖家”面板。 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. (不确定为什么会回声。)问题出在foreach循环内。 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. 而且我不确定基于http://www.w3schools.com/php/php_looping_for.asp我提供了什么有价值的参数,对于每个循环,我的代码排列是否正确。 What have I done wrong? 我做错了什么? Please help! 请帮忙!

foreach expects an array, and it gets a boolean. foreach期望一个数组,并且它得到一个布尔值。

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: 如果您想要一个字符串,则设置CURLOPT_RETURNTRANSFER,但是如果不成功,它仍然可以返回false,因此请确保检查以下内容:

 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. 例如,您可以使用explode()将字符串拆分为字符串数组,并参阅explode()文档中的“另请参阅”部分,以获取类似的有用功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM