php 将数组打印到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2628798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:09:23  来源:igfitidea点击:

Print array to a file

phpserialization

提问by Atif Mohammed Ameenuddin

I would like to print an array to a file.

我想将数组打印到文件中。

I would like the file to look exactly similar like how a code like this looks.

我希望文件看起来与这样的代码完全相似。

print_r ($abc);assuming $abc is an array.

print_r ($abc);假设 $abc 是一个数组。

Is there any one lines solution for this rather than regular for each look.

是否有任何一种解决方案,而不是每种外观的常规解决方案。

P.S - I currently use serialize but i want to make the files readable as readability is quite hard with serialized arrays.

PS - 我目前使用序列化,但我想让文件可读,因为序列化数组的可读性非常困难。

回答by Gordon

Either var_exportor set print_rto return the output instead of printing it.

要么 要么var_export设置print_r为返回输出而不是打印它。

Example from PHP manual

PHP 手册中的示例

$b = array (
    'm' => 'monkey', 
    'foo' => 'bar', 
    'x' => array ('x', 'y', 'z'));

$results = print_r($b, true); // $results now contains output from print_r

You can then save $resultswith file_put_contents. Or return it directly when writing to file:

然后您可以$results使用file_put_contents. 或者在写入文件时直接返回:

file_put_contents('filename.txt', print_r($b, true));

回答by Felix Kling

Just use print_r; ) Read the documentation:

只需使用print_r; )阅读文档

If you would like to capture the output of print_r(), use the returnparameter. When this parameter is set to TRUE, print_r()will return the information rather than print it.

如果您想捕获 的输出print_r(),请使用return参数。当此参数设置为 时TRUEprint_r()将返回信息而不是打印它。

So this is one possibility:

所以这是一种可能性:

$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($array, TRUE));
fclose($fp);

回答by binaryLV

file_put_contents($file, print_r($array, true), FILE_APPEND)

file_put_contents($file, print_r($array, true), FILE_APPEND)

回答by Sarfraz

You could try:

你可以试试:

$h = fopen('filename.txt', 'r+');
fwrite($h, var_export($your_array, true));

回答by alexwenzel

Quick and simple do this:

快速而简单地做到这一点:

file_put_contents($filename, var_export($myArray, true));

回答by Ahmad

You can try this, $myArrayas the Array

你可以试试这个,$myArray因为数组

$filename = "mylog.txt";
$text = "";
foreach($myArray as $key => $value)
{
    $text .= $key." : ".$value."\n";
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);

回答by Dieter Gribnitz

I just wrote this function to output an array as text:

我只是写了这个函数来输出一个数组作为文本:

Should output nicely formatted array.

应该输出格式良好的数组。

IMPORTANT NOTE:

重要的提示:

Beware of user input.

注意用户输入。

This script was created for internal use.

此脚本是为内部使用而创建的。

If you intend to use this for public use you will need to add some additional data validation to prevent script injection.

如果您打算将此用于公共用途,您将需要添加一些额外的数据验证以防止脚本注入。

This is not fool proof and should be used with trusted data only.

这不是万无一失的,应该仅用于受信任的数据。

The following function will output something like:

以下函数将输出如下内容:

$var = array(
  'primarykey' => array(
    'test' => array(
      'var' => array(
        1 => 99,
        2 => 500,
      ),
    ),
    'abc' => 'd',
  ),
);

here is the function (note: function is currently formatted for oop implementation.)

这是函数(注意:函数当前是为 oop 实现格式化的。)

  public function outArray($array, $lvl=0){
    $sub = $lvl+1;
    $return = "";
    if($lvl==null){
      $return = "\t$var = array(\n";  
    }
      foreach($array as $key => $mixed){
        $key = trim($key);
        if(!is_array($mixed)){
          $mixed = trim($mixed);
        }
        if(empty($key) && empty($mixed)){continue;}
        if(!is_numeric($key) && !empty($key)){
          if($key == "[]"){
            $key = null;
          } else {
            $key = "'".addslashes($key)."'";
          }
        }

        if($mixed === null){
          $mixed = 'null';
        } elseif($mixed === false){
          $mixed = 'false';
        } elseif($mixed === true){
          $mixed = 'true';
        } elseif($mixed === ""){
          $mixed = "''";
        } 

        //CONVERT STRINGS 'true', 'false' and 'null' TO true, false and null
        //uncomment if needed
        //elseif(!is_numeric($mixed) && !is_array($mixed) && !empty($mixed)){
        //  if($mixed != 'false' && $mixed != 'true' && $mixed != 'null'){
        //    $mixed = "'".addslashes($mixed)."'";
        //  }
        //}


        if(is_array($mixed)){
          if($key !== null){
            $return .= "\t".str_repeat("\t", $sub)."$key => array(\n";
            $return .= $this->outArray($mixed, $sub);
            $return .= "\t".str_repeat("\t", $sub)."),\n";
          } else {
            $return .= "\t".str_repeat("\t", $sub)."array(\n";
            $return .= $this->outArray($mixed, $sub);
            $return .= "\t".str_repeat("\t", $sub)."),\n";            
          }
        } else {
          if($key !== null){
            $return .= "\t".str_repeat("\t", $sub)."$key => $mixed,\n";
          } else {
            $return .= "\t".str_repeat("\t", $sub).$mixed.",\n";
          }
        }
    }
    if($lvl==null){
      $return .= "\t);\n";
    }
    return $return;
  }

Alternately you can use this script I also wrote a while ago:

或者,您可以使用我不久前也写过的这个脚本:

This one is nice to copy and paste parts of an array.

这个很适合复制和粘贴数组的一部分。

( Would be near impossible to do that with serialized output )

(使用序列化输出几乎不可能做到这一点)

Not the cleanest function but it gets the job done.

不是最干净的功能,但它完成了工作。

This one will output as follows:

这将输出如下:

$array['key']['key2'] = 'value';
$array['key']['key3'] = 'value2';
$array['x'] = 7;
$array['y']['z'] = 'abc';

Also take care for user input. Here is the code.

还要注意用户输入。这是代码。

public static function prArray($array, $path=false, $top=true) {
    $data = "";
    $delimiter = "~~|~~";
    $p = null;
    if(is_array($array)){
      foreach($array as $key => $a){
        if(!is_array($a) || empty($a)){
          if(is_array($a)){
            $data .= $path."['{$key}'] = array();".$delimiter;
          } else {
            $data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
          }
        } else {
          $data .= self::prArray($a, $path."['{$key}']", false);
        }    
      }
    }
    if($top){
      $return = "";
      foreach(explode($delimiter, $data) as $value){
        if(!empty($value)){
          $return .= '$array'.$value."<br>";
        }
      };
      echo $return;
    }
    return $data;
  }

回答by Patrick Mutwiri

just use file_put_contents('file',$myarray);file_put_contents() works with arrays too.

只需使用file_put_contents('file',$myarray);file_put_contents() 也适用于数组。

回答by vividus designs

However op needs to write array as it is on file I have landed this page to find out a solution where I can write a array to file and than can easily read later using php again.

但是,op 需要写入文件中的数组,我已经登陆此页面以找到一个解决方案,我可以在其中将数组写入文件,并且稍后可以再次使用 php 轻松读取。

I have found solution my self by using json_encode so anyone else is looking for the same here is the code:

我通过使用 json_encode 找到了自己的解决方案,所以其他人都在寻找相同的代码:

file_put_contents('array.tmp', json_encode($array));

than read

比阅读

$array = file_get_contents('array.tmp');
$array = json_decode($array,true);

回答by Sumit

Here is what I learned in last 17 hours which solved my problem while searching for a similar solution.

这是我在过去 17 小时内学到的东西,它在寻找类似解决方案的同时解决了我的问题。

resources:

资源:

http://php.net/manual/en/language.types.array.php

http://php.net/manual/en/language.types.array.php

Specific Code :

具体代码:

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

What I took from above, $arr[fruit] can go inside " " (double quotes) and be accepted as string by PHP for further processing.

我从上面得到的, $arr[fruit] 可以进入 " " (双引号) 并被 PHP 接受为字符串以进行进一步处理。

Second Resource is the code in one of the answers above:

第二个资源是上述答案之一中的代码:

file_put_contents($file, print_r($array, true), FILE_APPEND)

This is the second thing I didn't knew, FILE_APPEND.

这是我不知道的第二件事,FILE_APPEND。

What I was trying to achieve is get contents from a file, edit desired data and update the file with new data but after deleting old data.

我试图实现的是从文件中获取内容,编辑所需的数据并使用新数据更新文件,但在删除旧数据后。

Now I only need to know how to delete data from file before adding updated data.

现在我只需要知道如何在添加更新数据之前从文件中删除数据。

About other solutions:

关于其他解决方案:

Just so that it may be helpful to other people; when I tried var_exportor Print_ror Serializeor Json.Encode, I either got special characters like => or ; or ' or [] in the file or some kind of error. Tried too many things to remember all errors. So if someone may want to try them again (may have different scenario than mine), they may expect errors.

只是为了对其他人有所帮助;当我尝试var_exportPrint_rSerializeJson.Encode 时,我得到了像 => 或 ; 这样的特殊字符。或文件中的 ' 或 [] 或某种错误。尝试了太多事情来记住所有错误。因此,如果有人可能想再次尝试它们(可能与我的场景不同),他们可能会出现错误。

About reading file, editing and updating:

关于读取文件、编辑和更新:

I used fgets()function to load file array into a variable ($array)and then use unset($array[x])(where x stands for desired array number, 1,2,3 etc) to remove particular array. Then use array_values()to re-index and load the array into another variable and then use a while loopand above solutions to dump the array (without any special characters) into target file.

我使用fgets()函数将文件数组加载到变量 ($array) 中,然后使用unset($array[x])(其中 x 代表所需的数组编号,1,2,3 等)删除特定数组。然后使用array_values()重新索引并将数组加载到另一个变量中,然后使用while 循环和上述解决方案将数组(没有任何特殊字符)转储到目标文件中。

$x=0;

while ($x <= $lines-1) //$lines is count($array) i.e. number of lines in array $array
    {
        $txt= "$array[$x]";
        file_put_contents("file.txt", $txt, FILE_APPEND);
        $x++;
    }