我正在以以下方式读取一个txt文件:
$handle = fopen($captionTextFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo ($line);
}
fclose($handle);
}
// Output
IMAG0986.jpg|Title something 1 here|<b>Description</b><br />You can use HTML as you can see!
IMAG0988.jpg|Title something 2 here|<b>Description</b><br />You can use HTML as you can see!
etc...
现在,我只想在php数组中存储第一行|by之间的值。我打算拥有的示例:
$json = '{"IMAG0986.jpg": "Title something 1 here",
"IMAG0988.jpg": "Title something 2 here"}';
为了以后以这种方式访问此阵列:
$obj = json_decode($json);
print $obj->{'IMAG0986.jpg'}; // print: "Title something 1 here"
我遇到的问题是如何将值从行传递到数组?请帮忙吗?
使用file()将文件行读取到array
,然后使用带有|
分隔符的explode(),并将1st部分添加为key
,将2nd添加为value
到array
,最后使用json_encode()。
类似于:
<?php
$captionTextFile = "test.pipe";
$arrayFinal = array();
$lines = file($captionTextFile);
foreach($lines as $line) {
$array = explode("|", $line);
$arrayFinal[$array[0]] = $array[1];
}
print_r(json_encode($arrayFinal));
//{"IMAG0986.jpg":"Title something 1 here","IMAG0988.jpg":"Title something 2 here"}
//If you don't need json, just access the array by key:
echo $arrayFinal['IMAG0986.jpg'];
//Title something 1 here
您可以将行explode()
转换为对象中的键和值,以实现所需的JSON结果。
$data = new stdClass();
$handle = fopen($captionTextFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$row = explode('|', $line);
$data->{$row[0]} = row[1];
}
fclose($handle);
}
json_encode($data);