【问题标题】:PHP to insert into filePHP插入文件
【发布时间】:2016-05-12 08:07:18
【问题描述】:

我正在使用php 在文件中插入一些内容。我希望我要插入的内容在从顶部开始的 5 行之后插入到文件中。

如下是.txt 文件示例。

这是第一行

这是第二行

这是第三行

这是第四行

这是第 5 行

Here should be my content inserted with PHP
Here is my previous content inserted with PHP 

这是文件中的一些其他文本。

好吧,我可以插入但不能在我想要的行之后。我正在使用下面的 php 代码插入:-

<?php
$file = ( $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt' );;
$current = file_get_contents($file);
$current .= "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK\n";
file_put_contents($file, $current);
?>

【问题讨论】:

  • 无法理解。需要一个好的和简单的代码。
  • $contents = str_replace($contents, $fifth_line_text, $fifth_line_text . PHP_EOL . $content_to_insert) 怎么样?

标签: php


【解决方案1】:

试试这个:

<?php
    $test = "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK";
    $file = ( $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt' );
    $contents = explode("\n", file_get_contents($file), 6);
    file_put_contents($file, $contents[0]."\n".$contents[1]."\n".$contents[2]."\n".$contents[3]."\n".$contents[4]."\n".$test."\n".$contents[5]);
?>

【讨论】:

    【解决方案2】:

    您可以使用 file 将文件作为行数组获取,然后更改您需要的行,并将整个数据重写回文件。

    <?php
    $file = ( $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt' );;
    $current = file_get_contents($file);
    $current .= "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK\n";
    
    $line_i_need_to_change = 5-1; // Since line array starts from 0
    
    $lines = file( $file , FILE_IGNORE_NEW_LINES );
    
    $lines[$line_i_need_to_change] = $current.$lines[$line_i_need_to_change];
    
    //I noticed that $current have \n that helps to move the old data to next line 
    
    file_put_contents( $file , implode( "\n", $lines ) );
    
    ?>
    

    【讨论】:

      【解决方案3】:

      SKIP_LINES 表示你想跳过多少行。 您要添加的新内容应该是一个数组,以便正确处理。

      函数file() 完成这项工作。

      旧:

      <?php
      define('SKIP_LINES', 5); 
      $file = 'existing.txt';
      
      // read existing file into array
      $existing = file($file);
      
      // fill new array with existing data to SKIP_LINES
      $new = array();
      for ($i = 1; $i <= SKIP_LINES; $i++)
          $new[] = array_shift($existing);
      
      // this is the new content that you want to add (as array)                                                                   
      $addThis = file("newcontent.txt");
      
      // merge skipped 5 lines, new content, and the rest of the existing file
      $new = array_merge($new, $addThis, $existing);
      
      // write the new file
      file_put_contents($file, $new);
      

      编辑:

      版本已根据您的喜好调整。

      <?php
      define('SKIP_LINES', 5); 
      
      $file = $_SERVER['DOCUMENT_ROOT'] . '/sitemap.txt';                                                                                               
      
      // read existing file into array
      $existing = file($file);
      
      // add this array with the new content
      $addThis = [ "http://www.onlinedealsindia.in/deal/SOME-UNIQUE-LINK\n" ];
      
      /* splice array after SKIP_LINES. $existing now has Line 1-5 and $addThis
         $new contains all lines after the 5th (SKIP_LINES) line */
      $new = array_splice($existing, SKIP_LINES, 0, $addThis);
      
      // merge 5 lines with the new content and the other lines
      $new = array_merge($existing, $new);
      
      // write the new file
      file_put_contents($file, $new);
      

      【讨论】:

        【解决方案4】:
        $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
        

        }); var url="http://localhost/larasampleold/";

        $(函数() {

        var formgenre =$("#productForm");

        formgenre.validate({ // 忽略:':hidden:not([class~=selectized]),:hidden > .selectized, .selectize-control .selectize-input input',

        规则:{

        // banner_title:{
        
        //    required:true,
        
          // // trimWhiteSpace:true,
        
        //   remote:
        //             {
        
        //                 global: false,
        
        //                 url: base_url +"/title_exist",
        
        //                 type: "post",
        
        //                 data:
        //                         {
        //                             name: function () {
          
        //                                 return $('#banner_title').val();
        
        //                             }
        //                         }
        //             }, 
            
        // },
        
        // seo_keyword:{
        
        //     required:true
        
        // },
        

        // 图像:{

        // 扩展名: "jpeg,jpg,png,bmp",

        // 文件大小:20000000,

        // },

        },
        messages: {
        
        //     banner_title: {
        
        //     required: "Enter the banner title.",
        
        //      remote: "Banner title is already exist.",
        
        // },
        
        //     seo_keyword: {
          
        //         required: "Enter seo keyword.",
                
        //     }
        
        },
        

        focusInvalid:真,

        invalidHandler: function (form, validator) 
        {
            if (!validator.numberOfInvalids())
                
                return;
        
            validator.errorList[0].element.focus();
        
        },
        

        //errorElement: "span", //errorClass: "help-block help-block-error", 错误元素:“p”,

                errorClass: "invalid-feedback",
        
        errorPlacement: function (error, element) {
        
          
        
                   
           
                error.insertAfter(element);
                
                   
        },
        highlight: function (e) {
        
        $(e).closest(".form-group").addClass("has-error");
        
        },
        unhighlight: function (e) {
        
        $(e).closest(".form-group").removeClass("has-error");
        
        },
        success: function (e) {
        
        e.closest(".form-group").removeClass("has-error");
        
        },
        
        submitHandler: function (form) {
        
        if (formgenre.valid() == true) {
          
                // if(maxSize())
                // {
        var formData = new FormData(formgenre[0]);
            
            $.ajax({
            url: url +'employee/insert',
            type: "POST",
            dataType: "JSON",
            cache: false,
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
            if (response.rs) {
            //formcity[0].reset();
               window.location= url +'employee';
            } else {
            
            (response.errType == 'v') ? formgenre.prepend(showAlert('Required', response.msg)) : technoNotify('', response.msg, 'error');
            }
                
            } ,
            error: function (jqXHR, textStatus, errorThrown) {
            var $errmsg = '<p>Status code: ' + jqXHR.status + '</p><p>Error Thrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p>';
         
            console.log($errmsg);
            },
            beforeSend: function () {
            
            $('#axloader').show();
            },
            complete: function () {
            $('#axloader').hide();
            
            },
            timeout: 100000
            }).fail(function (jqXHR, textStatus) {
            if (textStatus === 'timeout') {
            console.log('Failed from timeout');
            }
            });
            
             
            }
        //}
            return false;
            }
            
            
            });
        
        });
            
        

        //文件上传

        if($request->hasFile('photo')) {

                $file=$request->file('photo');
        
                $extension=$file->getClientOriginalExtension();
               
        
                $filename="employee-".strtotime(date('Y-m-d H:i:S')).'.'.$extension;
        
                $file->move(base_path('public/employee'),$filename);
        
                $stud->photo=$filename;
              
            }
        

        【讨论】:

        • 请在回答问题时使用 HOW-TO 编写代码,不要过多的行空间。
        【解决方案5】:

        //标题

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
        
        <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
        
        <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
        
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
        
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
        
        <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
        
        <style type="text/css">
        
        .dataTables_processing {
        
            top: 64px !important;
        
            z-index: 11000 !important;
        
        }
        

        //删除数据

        $(document).on('click','.del_data',function(){

             var id=$(this).attr('id');
             
             $.ajax({
        
                   type:'delete',
        
                   url: url + '/' + id,
        
                   dataType:'JSON',
        
                   success:function(data)
        
                   {
        
                      alert(data.message);
        
                      bustype_tb.ajax.reload();
        
                   }
        
                });
        
          });
        

        //显示数据

        $data=EmployeeModel::find($id);

            return view('employee.view',compact('data')) ;
        

        //销毁

        $stud=EmployeeModel::find($id)->delete();

            return response()->json(['message'=>'deleted successfully'], 200);  
        

        //索引

        if($request->ajax())

            {
        
                $data = EmployeeModel::latest()->get();
        
                return DataTables::of($data)
        
                            ->addIndexColumn()
                           
                           ->addColumn('action', function($data){
                            $button = '<a href="empEdit/'.$data->id.'" > <button type="button" name="edit" id="'.$data->id.'" class="edit_data edit btn btn-primary btn-sm">Edit</button></a>';
        
                            $button .= '&nbsp;&nbsp;&nbsp;<button type="button" name="delete" id="'.$data->id.'" class="del_data delete btn btn-danger btn-sm">Delete</button>';
                            $button .= '&nbsp;&nbsp;&nbsp;<a class="dropdown-item" href="empView/'.$data->id.'" role="menuitem">
                            <i class="icon md-eye text-primary" aria-hidden="true"></i><button type="button" name="view" id="'.$data->id.'" class=" view btn btn-primary btn-sm">View</button></a>';
        
        
                            return $button;
        
                        })
        
                        ->rawColumns(['action'])
        
                        ->make(true);
        
            }
        
            return view('employee.list');
        

        //ajax 数据表

        var bustype_tb = '';

        $(函数 () {

        bustype_tb = $('#studtable').DataTable({

            processing: true,
        
            serverSide: true,
        
             ajax:{
        
               url: "{{ route('student.index') }}",
        
           },
        
            columns: [
                   
                     {
                        data: 'DT_RowIndex', 
        
                        name: 'DT_RowIndex',
        
                         orderable: false,
        
                         searchable: false
        
                         },
        
                     {
        
                         data: 'sname', 
        
                         name: 'sname' 
        
                         },
        
                     {
        
                         data: 'fname',
        
                          name: 'fname'
        
                           },
        
                     {
        
                         data: 'dob',
        
                          name: 'dob'
        
                           },
        
                 
                     {
        
                        data: 'action',
        
                         name: 'action', 
        
                         orderable: false
        
                   },
        
                  ],
        
         });
        
        
         bustype_tb.ajax.reload();
        

        });

        【讨论】:

          猜你喜欢
          • 2021-01-10
          • 2012-10-15
          • 2018-04-29
          • 1970-01-01
          • 1970-01-01
          • 2013-05-05
          • 2014-10-22
          • 1970-01-01
          • 2015-05-07
          相关资源
          最近更新 更多