【发布时间】:2018-01-22 01:06:12
【问题描述】:
我正在构建一个从外部源下载图像的函数,然后将每个已下载产品的 id 与 json 文件的路径一起写入,
下载循环正常工作,但当我尝试将产品 ID 和图像路径保存到文本文件时,仅保存第一条记录。
我尝试在使用file_put_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 );
};
这是 print_r ($result3) 的结果;
{"id":2977,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\2977.jpg"} {"id":2981,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\2981.jpg"} {"id":3009,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\3009.jpg"} {"id":3018,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\3018.jpg"} {"id":11531,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\11531.jpg"}
如您所见,Print_r 是正确的,我要做的就是将输出保存到文件中,目前这里是 file_put_contents 只有一个数组的结果:
{"id":11531,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\11531.jpg"}
你能帮忙告诉我做错了什么吗?我已经花了很多时间在这上面:)
【问题讨论】:
-
'methos'是错字吗?那应该是“方法”。 -
你在循环中保存,所以每次都覆盖
-
@rtfm 我已经尝试从循环外部保存它但得到相同的结果
-
因为你覆盖了循环内的变量