IT

배열을 파일로 인쇄

lottoking 2020. 5. 29. 08:13
반응형

배열을 파일로 인쇄


배열을 파일로 인쇄하고 싶습니다.

파일이 이와 비슷한 모양과 정확히 똑같이 보이기를 원합니다.

print_r ($abc); $ abc가 배열이라고 가정합니다.

각 모양마다 규칙적인 것이 아니라 하나의 라인 솔루션이 있습니까?

추신-현재 직렬화를 사용하고 있지만 직렬화 된 배열에서는 가독성이 매우 어렵 기 때문에 파일을 읽을 수있게하고 싶습니다.


하나 var_export또는 설정 print_r을 인쇄하는 대신 출력을 반환합니다.

PHP 매뉴얼의 예

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

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

그런 다음 저장할 수 있습니다 $resultsfile_put_contents. 또는 파일에 쓸 때 직접 반환하십시오.

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

그냥 사용하십시오 print_r; ) 설명서를 읽으십시오 :

의 출력을 캡처 print_r()하려면 return매개 변수를 사용하십시오 . 이 매개 변수로 설정하면 TRUE, print_r()정보를 반환하는 대신 그것을 인쇄 할 수 있습니다.

따라서 이것은 하나의 가능성입니다.

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

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


시도해 볼 수 있습니다 :

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

빠르고 간단한 작업 :

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

$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);

방금 텍스트로 배열을 출력하기 위해이 함수를 작성했습니다.

좋은 형식의 배열을 출력해야합니다.

중요 사항:

사용자 입력에주의하십시오.

이 스크립트는 내부 용으로 작성되었습니다.

공용으로 사용하려는 경우 스크립트 삽입을 방지하기 위해 추가 데이터 유효성 검사를 추가해야합니다.

이것은 확실한 증거가 아니며 신뢰할 수있는 데이터에만 사용해야합니다.

다음 함수는 다음과 같이 출력됩니다 :

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

다음은 함수입니다 (참고 : 함수는 현재 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;
  }

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


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

resources:

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.

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.

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_export or Print_r or Serialize or 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.

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 loop and above solutions to dump the array (without any special characters) into target file.

$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++;
    }

Below Should work nice and more readable using <pre>

<?php 

ob_start();
echo '<pre>';
print_r($array);
$outputBuffer = ob_get_contents();
ob_end_flush();
file_put_contents('your file name', $outputBuffer);
?>

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.

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

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

than read

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

참고URL : https://stackoverflow.com/questions/2628798/print-array-to-a-file

반응형