如何在csv文件中使用php在特定位置插入值 [英] how to insert value in a particular location in csv file using php

查看:231
本文介绍了如何在csv文件中使用php在特定位置插入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用PHP在CSV文件中的特定位置写入?

Is it possible to write at a particular location in a CSV file using PHP?

我不想在CSV文件的末尾追加数据。

I don't want to append data at the end of the CSV file. But I want to add data at the end of a row already having values in the CSV.

提前感谢

推荐答案

在那里。完成工作代码:

There you go. Complete working code:

<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
    $array2 = array_splice($array, $pos);
    $array[] = $val;
    $array = array_merge($array, $array2);

    return $array;
}

//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;

//Full path & Name of the CSV File
$FileName = 'data.csv';

//Read the file and get is as a array of lines.
$arrLines = file($FileName);

//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);

//Convert result array to string.
$ResultStr = implode("\n", $Result);

//Write to the file.
file_put_contents($FileName, $ResultStr);
?>

这篇关于如何在csv文件中使用php在特定位置插入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆