2016-04-30 38 views
1

我读以下方式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数组中。什么我打算例子有:

$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" 

说我有是如何传递的值从线的问题数组?请帮忙吗?

+0

'fgetcsv()'与'|'然后用'$线[0]'和'$线[1]'或简单地'爆炸()'目前的'$ line'。 – AbraCadaver

回答

1

使用file()读取文件行的​​array,然后用explode()|分隔符和key第二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 

1

您可以将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); 
+0

不错的答案,但你可以通过使用'file'而不是'fopen'来改善它 –

相关问题