PHP - Using Fgetcsv On Multiple Line Csv
Hey all,
I've run into a bit of a problem when trying to use fgetcsv to dump the contents of a csv file into an array, in as much as fgetcsv stops after a line break. I've been using fputcsv to add content to the file and every time I use fputcsv it adds a line break, hense my problem. As you might have guessed from the time of this post (I'm in the uk) I've been trying to come up with a solution for this for quite a while; I'm pretty new to php as you might have gathered. Code: <?php $fname=data.csv $file=fopen($fname,"r"); $data=fgetcsv($file); echo "$data[0] $data[1] $data[2]"; ?> The csv looks something like this: adam,19 alex,16 andrew,24 etc... I'm able to access the first 2 values with $data[0] and $data[1], but when I try and access anything after the first line break, I get undefined ofset errors. If anyone could point me in the right direction to a solution for this problem I would be extremely greatful since I can't seem to find anything!! In the mean time, I'm off to catch up on some sleep. Cheers. Similar Tutorials
My .csv file has 3 columns and 10 rows $file = fopen('document.csv', 'r'); while (($data = fgetcsv($file)) !== FALSE) { $string .= $data[0].','.$data[1].','.$data[2]."\n"; } print $string; If I open the original .csv file in a text editor and replace all the invisible end-of-line "\r" with "\n" then the above code works fine. There must be an efficient way to implement this in my script, without having to remember to modify the original .csv file first.... Thank you in advance 😀 I am trying to display rows starting with a specific tag when using fgetcsv() like rows starting with tag SY or AP where the first element of each such rows would have SY or AP has prefix example SY-Atlanta, SY-Texas, AP-Atlanta, AP-texas. The next columns in that row would have some data. I want to display only rows with above said prefix. What is the best way to do it? Use preg_match for each row and display it only if it has a match or is there any easier way? Sample data in csv: SY-Atlanta,0,0,0,5,9,9,0 SY-Texas,0,5,8,0,0,8.4 AP-Atlanta,9,4,8,9,0,0,0 AP-Texas,8,0,9,0,0,0,0 DF-Atlanta,8,4,9,3,0,0,0,0 DF-Texas,8,4,9,0,0,0,0,0 Hi I am uploading a csv file in the datbase. and i want to show an error message if the columns are more than 5. I am counting the rows in the below script but it always prints row 1. I have spent lot of time to figure out and google it. all the examples in google looks similar to mine. Can anyone find any issue with the below script and correct me pls Thanks in advance $row=1; $error = 'No'; //////////initialise the error flag while (($data = fgetcsv($handle, 1000, ",",'"')) !== FALSE) { if( count($data) > 5 ){ //print_r($data); $error = 'Yes' ; ///////////set the error flag to yes and break the loop . validation failed $errorMess = 'There are more than 5 columns in row # '.$row ; break ; } ///////////////insert the data into stagging table if the column ==5/////////////////// //print_r($data); $sqlLoad = "INSERT INTO ratecodes_stagging ( package_name,package_table,plan_name,plan_code,package_hierachy ) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."','".addslashes($data[2])."','".addslashes($data[3])."', '".addslashes($data[4])."')"; $resultSqlLoad = es_query($sqlLoad); $row++; //echo $i."<br>"; }//END while fgetcsv Anyone can help me with plotting of multiple line graph in php. I have researched on multiple line graph online and I would like to plot the graph by taking data from my database but the example below is inserting the graph data manually. Anyone can teach me how to use a for loop inside an array? Code: [Select] <?php //Include the code require_once 'phplot.php'; //Define the object $plot = new PHPlot(800,600); //Set titles $plot->SetTitle("A 3-Line Plot\nMade with PHPlot"); $plot->SetXTitle('X Data'); $plot->SetYTitle('Y Data'); //Define some data $example_data = array( array('a',3,4,2), array('b',5,3,1), array('c',7,2,6), array('d',8,1,4), array('e',2,4,6), array('f',6,4,5), array('g',7,2,3) ); $plot->SetDataValues($example_data); //Turn off X axis ticks and labels because they get in the way: $plot->SetXTickLabelPos('none'); $plot->SetXTickPos('none'); //Draw it $plot->DrawGraph(); ?> I am a web designer/PHP hack trying to solve a problem for our HR department. We have a quarterly newsletter in a Wordpress site I developed and they want to have a dynamically updated service anniversary page updated through excel. The solution to this problem is clearly fgetcsv, but I'm having trouble understanding how to implement it within the wordpress page. Here is a really nice function from the php manual page Code: [Select] <?php function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) { if (($handle = fopen("$source_file", "r")) !== FALSE) { $columns = fgetcsv($handle, $max_line_length, ","); foreach ($columns as &$column) { $column = str_replace(".","",$column); } $insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES"; while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) { while (count($data)<count($columns)) array_push($data, NULL); $query = "$insert_query_prefix (".join(",",quote_all_array($data)).");"; mysql_query($query); } fclose($handle); } } function quote_all_array($values) { foreach ($values as $key=>$value) if (is_array($value)) $values[$key] = quote_all_array($value); else $values[$key] = quote_all($value); return $values; } function quote_all($value) { if (is_null($value)) return "NULL"; $value = "'" . mysql_real_escape_string($value) . "'"; return $value; } ?> But this leaves me with a few questions: 1. is this both function AND query? or do i need extra code to run the function and spit out the results? 2. where do i input my actual values? 3. does this have to mirror a mysql table somewhere else? i feel like i'm missing a crucial piece of info here. the path to the csv file needs to be absolute, due to HR needing to manage the file themselves without the help of yours truly. the intended output will look like this: 5 YEARS FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3, etc 6 YEARS FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3, etc and so on. so in addition to the FirstName, LastName and Year columns, the loop will need to include a conditional statement. something like: Code: [Select] <h1>5 YEAR</h1> <ul> <?php if (quote_all_array(5) ) : ?> echo "<li>(FirstName, LastName), </li>"; <?php endif; ?> </ul> <h1>6 YEAR</h1> <ul> <?php if (quote_all_array(6) ) : ?> echo "<li>(FirstName, LastName), </li>"; <?php endif; ?> </ul> I'm sure my syntax is horribly wrong because I have virtually no idea what I'm doing. Which is why I'm asking you all for help to help my understanding i'll supply a set of variables: CSV Source: http://resource.mysite.com/anny.csv Table Columns: FirstName, LastName, Year External MySql database (should it apply): AnnySql Thanks in advance for any help. I'm over my pay grade on this one. Hi I am trying to use this function to upload a CSV-format baseball schedule. I copied the example code from the manual website and it worked fine, printing out the contents, array style. I then added my code to the middle of this which just does a bit of analysis of dates and times for unix-style and then writes the stuff into a MySQL DB. It didn't work any more. As soon as I try to use fgetcsv it won't work. PLEASE HELP I have pulled all my remaining hair out! I checked my code with a magnifying glass but any hint of my code near fgetcsv stops the page loading. hi I am trying to add a few line of code using fopen It works and it adds the lines but I have multiple occurrence of this line and I would like to all be amended. $target_line='$second = (int)substr($raw_date, 17, 2);'; $lines_to_add= '$raw_datetime = translate_from_gregorian($raw_datetime);'. PHP_EOL. '$year = (int)substr($raw_datetime, 0, 4);'. PHP_EOL. '$month = (int)substr($raw_datetime, 5, 2);'. PHP_EOL. '$day = (int)substr($raw_datetime, 8, 2);'. PHP_EOL; $config ='includes/functions/general.php'; $file=fopen($config,"r+") or exit("Unable to open file!"); $insertPos=0; // variable for saving //Users position while (!feof($file)) { $line=fgets($file); if (strpos($line,$target_line)!==false) { $insertPos=ftell($file); // ftell will tell the position where the pointer moved, here is the new line after //Users. $newline = $lines_to_add; } else { $newline.=$line; // append existing data with new data of user } } fseek($file,$insertPos); // move pointer to the file position where we saved above fwrite($file, $newline); fclose($file);  help me please, my code is :
$table = tov; $hal = $_GET[hal]; if(!isset($_GET['hal'])){ $page = 1; } else { $page = $_GET['hal']; } $max_results = 2; $from = (($page * $max_results) - $max_results); $sql = mysql_query("SELECT * FROM $table ORDER BY id_berita DESC LIMIT $from, $max_results"); while($hs_show = mysql_fetch_array($sql)){ $urut++; ?> <marquee scrollamount="4" align="left" behavior="scroll" direction="left" class="text" onmouseover="this.stop()" onmouseout="this.start()"> <?php echo "$hs_show[judul]"; ?> </marquee> <?php } $total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM $table"),0); $total_pages = ceil($total_results / $max_results); i want the results to be in 1 line and one after the other ,thanks I have data in a flat file that looks like the following: Code: [Select] ##### BEGIN PRODUCT LOOP ##### REF*19**OHIO VALLEY FLOORING PID*F*TRN***SUPERINTENDENT PID*F*MAC***CARINDR MEA**LN*125.0*FT MEA**WD*12.0*FT MEA**SW*0.500*FP CTP**PRICE1*9.790**SY****ST CTP**PRICE2*11.190**SY****CT ####### BEGIN INTERNAL LOOP ####### G43*003**INVENTORY SLN*1**O******SK*RKDA100AA591*****ST*A100A PID*F*COLOR***SAGE TWEED PID*F*35***A591 SLN*2**O******SK*RKDA100AA592*****ST*A100A PID*F*COLOR***CREAMY TOFFEE PID*F*35***A592 SLN*3**O******SK*RKDA100AA593*****ST*A100A PID*F*COLOR***GALAXY GRAY PID*F*35***A593 ######## END INTERNAL LOOP ######## LIN**GS*A161*MF*ROOKWOOD CARPET*ST*A161 DTM*007*20110413 ####### END PRODUCT LOOP ####### My problem is that the header information is on each line and not at the beginning of the file like most CSV formats. Like the following: Code: [Select] REF*19 (Would be a column in the database) --- I would need OHIO VALLEY FLOORING but for each Referenced SKU # PID*F*TRN (Would be a column in the database) --- I would need SUPERINTENDENT but for each Referenced SKU # PID*F*MAC (Would be a column in the database) --- I would need CARINDR but for each Referenced SKU # and so on... So the database output would look something like: [/code] SKU | PRICE1 | PRICE2 | COLOR ---------------------------|-------------------|---------------|------------------ RKDA100AA591 | 9.790 | 11.190 | SAGE TWEED RKDA100AA592 | 9.790 | 11.190 | CREAMY TOFFEE RKDA100AA593 | 9.790 | 11.190 | GALAXY GRAY [/code] How would I define each row in the data set and get the information for each row to stuff in the database? Thanks for any help you can provide. This is what I have at present: Code: [Select] print_r(buildStock('832x12Data.txt')); function buildStock($File) { $handle = fopen($File, "r"); $fields = fgetcsv($handle, 1000, ","); while($data = fgetcsv($handle, 1000, ",")) { $detail[] = $data; } $x = 0; $y = 0; foreach($detail as $i) { foreach($fields as $z) { $stock[$x][$z] = $i[$y]; $y++; } $y = 0; $x++; } return $stock; } Hello, I have a page where the user uploads a CSV file and I want to read that CSV and update database fields accordingly. It seems I have all the code correct but only the first row of the CSV is being imported. If I echo my variables within the loop, the only output is the first row of the CSV - no subsequent rows. I feel like I'm close but not sure what the issue is? Thanks a million for any help!! Jason //START FILE OPERATION $handle = fopen('uploads/testfile.csv', "r"); //LOOP CONTENTS OF CSV FILE while (($data = fgetcsv($handle, 1000, ",")) !== false) { $importID = $data[0]; $companyName = $data[1]; $primaryPhone = $data[2]; $primaryEmail = $data[3]; $billingFirstName = $data[4]; $billingLastName = $data[5]; $query = 'SELECT importID FROM import'; if (!$result = mysql_query($query)) { continue; } if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { //UPDATE IF ENTRY EXISTS $query = "UPDATE import SET companyName='$companyName', primaryPhone='$primaryPhone', primaryEmail='$primaryEmail', billingFirstName='$billingFirstName' WHERE importID=$importID"; mysql_query($query); if (mysql_affected_rows() <= 0) { //NO RECORDS UPDATED } } else { //ENTRY DOESN'T EXIST } mysql_free_result($result); } //CLOSE FILE OPERATION fclose($handle);
Sometimes my 3 column .csv file has commas within quotes: When I use this code, I need the data count to stay the same "3" for each row: while (($data = fgetcsv($handle,2000,',')) !== FALSE) { print count($data); // prints "3" ... then prints "4" .... then prints "3" }
Thank you. Edited April 15, 2020 by StevenOliverI have ascript that loops through a directory of zip files, unzips to new directory and deletes the zip file and is supposed to import to mysql database. Everything works BUT writes empty records. Here is my code if anyone can help would be great Code: [Select] <?php include("sharons_dbinfo.inc.php"); $files = glob('gz/*.gz'); $texts = glob('*.txt'); foreach ($files as $in_file) { $file=str_replace(".gz","",$in_file); $file=str_replace("gz/","",$file); $file2=fopen($file,"w"); $gz = gzopen($in_file, 'r'); while (!gzeof($gz)) { $contents = gzread($gz, 10000); fwrite($file2, $contents); } gzclose($gz); unlink ($in_file); foreach ($texts as $text) { $handle = fopen("$text", "r"); while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) { $data = str_replace("'", "", $data); mysql_connect(localhost,$user,$password); mysql_select_db($database) or die( "Unable to select database"); $import="INSERT into new (`ID`,`PROGRAMNAME`,`PROGRAMURL`,`CATALOGNAME`,`LASTUPDATED`,`NAME`,`KEYWORDS`,`DESCRIPTION`,`SKU`,`MANUFACTURER`,`MANUFACTURERID`,`UPC`,`ISBN`,`CURRENCY`,`SALEPRICE`,`PRICE`,`RETAILPRICE`,`FROMPRICE`,`BUYURL`,`IMPRESSIONURL`,`IMAGEURL`,`ADVERTISERCATEGORY`,`THIRDPARTYID`,`THIRDPARTYCATEGORY`,`AUTHOR`,`ARTIST`,`TITLE`,`PUBLISHER`,`LABEL`,`FORMAT`,`SPECIAL`,`GIFT`,`PROMOTIONALTEXT`,`STARTDATE`,`ENDDATE`,`OFFLINE`,`ONLINE`,`INSTOCK`,`CONDITION`,`WARRANTY`,`STANDARDSHIPPINGCOST`) values('','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]','$data[36]','$data[37]','$data[38]','$data[39]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); } } ?>Thanks everyone Hi, I'm modifying the following PHP code from a Wordpress plugin: /* Byline. */ if ( $instance['byline'] ) echo do_shortcode( "<p class='byline'>{$instance['byline']}</p>" ); /* Entry title. */ if ( 'widget' !== $instance['entry_container'] && $instance['entry_title'] && $show_entry_title ) { the_title( "<{$instance['entry_title']} class='entry-title'><a href='" . get_permalink() . "' title='" . the_title_attribute( 'echo=0' ) . "' rel='bookmark'>", "</a></{$instance['entry_title']}>" ); } elseif ( 'widget' !== $instance['entry_container'] && $show_entry_title ) { the_title( "<a href='" . get_permalink() . "' title='" . the_title_attribute( 'echo=0' ) . "' rel='bookmark'>", "</a>" ); } The output currently is: Code: [Select] [ December 13, 2010 ] Post Title I'm trying to combine the two so that the output appears on one line. What is the operator to execute multiple command in one statement? Thanks. i have a mysql table which contains name like mid mname 101 AAA 102 BBB 103 CCC now i have to print this name in a html table like AAA, BBB, CCC i am getting this by while loop in a variable but when loop changes then value also change so please tell me how i get this only in one variable & print what im trying to do is take a youtube embed code find the URL code for that video and remove all other parts of the code keeping only the URL of the video after i get the URL by it self then replace the http://www.youtube.com/ part of the URL with http://i2.ytimg.com/vi/ to do this i know that i need something like this to get the URL of the video http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+) but how to only return just the URL is something idk how to do then use str_replace http://www.youtube.com/(?:v|cp)/" with http://i2.ytimg.com/vi/ so in the end im asking if anyone know how to remove all other codes i dont want and only keep the URL this may have to be done using "regex" im not sure as i dont know to much about regex and what it can do but does sound like it would help lol i have to read a single line from a csv, its a really big file and i only need one column.
i need the response to be a string ,i made a search and found the following code but i dont have any idea how to get a single line from a single string per run .
<?php $row = 1; //open the file if (($handle = fopen("file.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } ?> Edited by bores_escalovsk, 16 May 2014 - 06:38 PM. Dear All Good Day, i am new to PHP (a beautiful server side scripting language). i want to send a mail with line by line message i tried with different types like by placing the things in table and using <br /> but the thing is the tags are also visible in the message of the mail. Here is my code: $message1 = "Name :". $_REQUEST['name']."<br />"; $message1 .= "Surname :". $_REQUEST['surname']."<br />"; $message1 .= "Cellphone :". $_REQUEST['mobileno']."<br />"; $message1 .= "Telephone :". $_REQUEST['landno']."<br />"; $message1 .= "Fax :". $_REQUEST['fax']."<br />"; $message1 .= "Company :". $_REQUEST['company']."<br />"; $message1 .= "Email :". $_REQUEST['email']."<br />"; $message1 .= "Country :". $_REQUEST['country']."<br />"; $message1 .= "Enquity :". $_REQUEST['enquiry']."<br />"; $message1 .= "Date&Time :". $date."<br />"; For this code if try to print/echo it it is working fine it is displaying line by line, but using this variable ($message1) in the mail these <br /> are also visible. Can any one guide me to resolve(to remove these tags from the message part) this issue. Thanks in Advance. :confused: Hi. I want a simple textbox, that when submited, will replace very every new line, with the <br> tag. What will happen, when it submits, it will take the contents of a textbox, add the <br> tag where a new line is suposed to be, and save the string to a MySQL Database. I think this is the easiest way of allowing a user to edit what appears on a website when logged in, but if there is a easier way, then please tell me. What I am trying to do, is a login page, and once logged in, you enter new text into the textbox, click submit, and on the website homepage, the main text will change to what was submitted. But if there is a new line, I think the only way in HTML to make one is to put a <br> tag, so I want the PHP to but that tag wherever there is a new line. Sorry if I am confusing, I am not that advanced at PHP, but I would be very happy if you could supply me with the correct code. Time is running out... If you do not understand me, please tell me -- PHPLeader (not) How to get this echo line to display as one line? No matter what I have done it displays as two lines. I even tried <nobr></nobr> Teachers Name: John Jones $userid = mysql_real_escape_string($_GET['user_id']); $sql = "select * from users where `id`='$userid' "; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<h3>Teachers Name: </h3>" . $row["first_name"] . " " . $row["last_name"] ; } Thanks for your help. I have a script that reads a .gz file into an array and prints the name of each record but will not work on larger files. Is there a way to read 1 line at a time? Here is the code I have so far. Code: [Select] <?php if ($handle = opendir('.')) { print "<ol>"; while (false !== ($file = readdir($handle))) { if($file != '..' && $file!="." && $file!="start_update.php" && $file!="sharons_dbinfo.inc.php" && $file!="root.php" && $file!="read_directory.php" && $file!="read_dir.php" && $file!="new_category.php" && $file!="index.php" && $file!="file_count.php" && $file!="dir_loop2.php" && $file!="dir_loop1.php" && $file!=".htaccess" && $file!="Answer.txt" && $file!="Crucial_Technology-Crucial_US_Product_Catalog_Data_Feed.txt"){ $filename = $file; $go = filesize($filename); if($go >= 1){ $filename2 = explode("-", $filename); $filename2 = $filename2[0]; echo str_replace("_"," ",$filename2) . ' | Filesize is: ' . filesize($filename) . ' bytes<br>'; $gz = gzopen($filename, 'r'); $lines = gzfile($filename,10000); foreach ($lines as $line) { $line2 = explode(",", $line); $line2 = str_replace("," , "-" , $line2); echo "<li>".str_replace("," , "-" , $line2[4])."</li><br>"; } } } } closedir($handle); } ?> </ol> |