从file_get_contents()值创建数组

时间:2016-05-13 15:16:04

标签: php arrays file-get-contents

socallink.txt:

  

" Facebook和#34;"微博""微博""谷歌加"" YouTube和#34 ;, " Pinterest的""的Instagram"

PHP:

$file = file_get_contents('./Temp/socallink.txt', true);
$a1 = array($file);
print_r($a1);

结果:

Array
(
    [0] => "Facebook","Twitter","Twitter","google-plus","youtube","pinterest","instagram"
)

需要:

$a1['0']=facebook;
$a1['1']=Twitter;

3 个答案:

答案 0 :(得分:6)

这解决了您的问题:

$file = '"Facebook","Twitter","Twitter","googleplus","youtube","pinterest","instagram"'; // This is your file

首先删除所有“。

$file = str_replace('"', '', $file);

然后每次都爆炸,

$array = explode(',',$file);

var_dump($array)给出:

array(7) {
  [0]=>
  string(8) "Facebook"
  [1]=>
  string(7) "Twitter"
  [2]=>
  string(7) "Twitter"
  [3]=>
  string(11) "google-plus"
  [4]=>
  string(7) "youtube"
  [5]=>
  string(9) "pinterest"
  [6]=>
  string(9) "instagram"
}

全球代码如下:

$file = file_get_contents('./Temp/socallink.txt', true);
$file = str_replace('"', '', $file);
$a1 = explode(',',$file);

希望这会有所帮助

答案 1 :(得分:0)

由于这些是逗号分隔值(CSV),这可能是最简单的:

$file = file_get_contents('./Temp/socallink.txt', true);
$a1   = str_getcsv($file);

答案 2 :(得分:-1)

<?php
//fetch the file content
    $file =  file_get_contents('your file path`enter code here`');

 //create an array by breaking the string into array values at the comma ',' point
$a = explode(',',$file);

print_r($a);

//result
// Array ([0] => "Facebook"
// [1] => "Twitter"
// [2] => "Twitter"
// [3] => "google-plus"
// [4] => "youtube"
// [5] => "pinterest"
// [6] => "instagram" )