收到以下错误“警告:为foreach()提供的参数无效”

时间:2017-01-13 04:32:48

标签: php xml

这里有什么问题?获得第二行的错误(foreach ....)有人可以帮我纠正吗?更新:我认为我的问题是XML文件没有加载。我需要先纠正它。

 $xml = simplexml_load_string($result);              

    foreach($xml->statusCode as $statusCode){
            if($statusCode != '200'){
                echo $failureMessage; 
                echo 'Error: <span class="formerror">'; 
                echo $xml->errorMessage;                
                echo '</span>';
            } else {
                echo $successMessage. 
                '<ul>
                    <li>First Name: '.$c['f_name'].'</li>
                    <li>Last Name: '.$c['l_name'].'</li>
                    <li>Your Zipcode: '.$c['zipcode'].'</li>
                    <li>Your Email: '.$c['email'].'</li>
                    <li>Your Phone Number: '.$c['phone'].'</li>';
                if($c['comments'] != ''){ 
                    echo '<li>'.$c['comments'].'</li></ul>';
                } else {
                    echo '</ul>';
                }
                ?>

1 个答案:

答案 0 :(得分:0)

  

收到以下错误“警告:提供的参数无效   foreach()“

因为nullfalse

foreach($xml->statusCode as $statusCode){ 
             ^
            see var_dump($xml->statusCode), 
            since $xml is either null or false you get above error

我们可以像这样重新生成此错误,例如

$ php -r 'foreach(null as $e){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

/*false OR FALSE*/
$ php -r 'foreach(false as $e){}'
PHP Warning:  Invalid argument supplied for foreach() in Command line code on line 1

所以你需要先处理错误

if ($xml === FALSE) 
{
    throw new Exception('Failed to load XML string.');
}else
{ 
     foreach($xml->statusCode as $statusCode)
     { 
             /* Remaining code goes here */
     }
}