Php foreach仅保存第一个数组,甚至打印\r正确打印结果我缺少的内容

Php foreach仅保存第一个数组,甚至打印\r正确打印结果我缺少的内容,php,arrays,json,foreach,Php,Arrays,Json,Foreach,我正在构建一个函数,从外部源下载图像,然后写下下载的每个产品的id以及json文件的路径 下载循环工作正常,但当我试图将产品id和图像路径保存到文本文件时,仅保存第一条记录 在使用file\u put\u contents函数之前,我尝试打印输出,结果显示得到了正确的结果。我想知道为什么只保存第一个结果而不是所有结果 我几乎花了一整天的时间想弄明白,但运气不好。任何帮助都将不胜感激 这是我的密码: $url = 'product-test2.json'; // path

我正在构建一个函数,从外部源下载图像,然后写下下载的每个产品的id以及json文件的路径

下载循环工作正常,但当我试图将产品id和图像路径保存到文本文件时,仅保存第一条记录

在使用
file\u put\u contents
函数之前,我尝试打印输出,结果显示得到了正确的结果。我想知道为什么只保存第一个结果而不是所有结果

我几乎花了一整天的时间想弄明白,但运气不好。任何帮助都将不胜感激

这是我的密码:

            $url = 'product-test2.json'; // path to  JSON file
            $data = file_get_contents($url);
            $characters = json_decode($data, true); 
            $i = array_column ($characters , 'Id');

            foreach ( $i as $value => $productid){
            include 'login.php';
            $url = "http://xxxx.com/api/products/image/";
            $url .= implode($matches [0]); // get the token form login.php
            $url .= '/' . $productid ;    //product id 
            // echo $url . '<br>';
            $opts = array ('http' => array ( 
                         'methos' => 'GET',
                         'header' => 'Content-typpe: application/json',
                         )
            );
            $context = stream_context_create ($opts);
            $urlImage = file_get_contents ($url , false , $context);
            $urlImage = substr_replace ($urlImage , "",-1);
            $urlImage = substr ($urlImage , 1);
            $fopenpath = 'C:\\xampp\htdocs\\test\\api\\images\\'   ;
            $fopenpath .= $productid . '.jpg';        
            $fp = fopen ( $fopenpath, 'w');
            $c = curl_init ($urlImage);    
            curl_setopt ($c , CURLOPT_FILE , $fp);
            curl_setopt ($c , CURLOPT_HEADER, 0);
            curl_setopt ($c , CURLOPT_POST, false);
            curl_setopt ($c , CURLOPT_SSL_VERIFYPEER, false);
            $rawdata = curl_exec ($c);
            fwrite ($fp, $rawdata);
            fclose ($fp);
            //
            $result3= ["id" => $productid ,"image_path" => $fopenpath]  ; 


            $image_file = "images.json";
            $output = json_encode ($result3);   
                print_r ($output);
            file_put_contents ($image_file , $output );  


            };
正如您所看到的,打印是正确的,我要做的就是将输出保存到文件中,现在这里是文件内容的结果,只有一个数组:

{"id":11531,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\11531.jpg"}

你能告诉我我做错了什么吗?我已经在这上面花了很多时间:)

文件内容与打开、写入和关闭文件是一样的,在foreach循环中这样做没有意义。如果您真的想使用它,我认为您可以添加FILE_APPEND标志,这将阻止它一次又一次地覆盖自身


另一种方法是在foreach循环之前使用“a”标志进行fopen,这将创建文件,然后继续追加行,而不是在每个循环中删除文件内容。(和foreach后面的fclose。)

'methodos'
这是打字错误吗?这应该是“方法”。你在循环中的保存,所以覆盖每个time@rtfm我已经尝试从循环之外保存它,但是我得到了同样的结果,因为你在环内写了变量。你是正确的100%谢谢。@ SeasAMRun.我刚刚添加了FielyAppEngult,它的工作我将考虑使用FOpen::)Kasalo做了更多的感觉来追加变量和写。ONCE@rtfm感谢您的建议,我将尝试您的解决方案:)
{"id":11531,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\11531.jpg"}