Jump to content

Search the Community

Showing results for tags 'csv'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I am trying to write post variables to a csv file but it writes everything in one line separated by comma <?php $list= array($_POST['purchases']); $file = fopen("purchases.csv", "w"); foreach ($list as $line) { fputcsv($file, $line); } fclose($file); ?> Result in purchases.csv file Marilyn,Nancy,Johan,Carol,Juanic,Shirley But I want every string value on separated line Marilyn Nancy Johan Carol Juanic Shirley
  2. i was working on a mini project that imports csv file to the database through ajax and it's working fine <?php if(!empty($_FILES["marks_file"]["name"])) { $connect = mysqli_connect("localhost", "root", "", "dbname"); $output = ''; $allowed_ext = array("csv"); $extension = end(explode(".", $_FILES["marks_file"]["name"])); if(in_array($extension, $allowed_ext)) { $file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r'); fgetcsv($file_data); while($row = fgetcsv($file_data)) { $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } $select = "SELECT * FROM csv ORDER BY id DESC"; $result = mysqli_query($connect, $select); $output .= ' <table class="table table-bordered"> <tr> <th width="25%" >name</th> <th width="15%" >Physics</th> <th width="15%" >Maths</th> <th width="15%" >Chemistry</th> <th width="15%" >Biology</th> <th width="15%" >SST</th> </tr> '; while($row = mysqli_fetch_array($result)) { $output .= ' <tr> <td>'.$row["name"].'</td> <td>'.$row["Physics"].'</td> <td>'.$row["Maths"].'</td> <td>'.$row["Chemistry"].'</td> <td>'.$row["Biology"].'</td> <td>'.$row["SST"].'</td> </tr> '; } $output .= '</table>'; echo $output; } else { echo 'errorx'; } } else { echo "errory"; } ?> however the imported csv files inserts null values in the tables because the format of all csv files assigned to me are in the exact same format: ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100 ,,,Name1,10,25,35,42,62 ,,,Name2,80,45,45,45,25 ,,,Name3,63,25,63,36,36 ,,,Name4,82,36,75,48,42 ,,,Name5,45,45,78,25,24 ,,,Name6,36,36,15,75,36 ,,,Name7,99,45,24,24,45 ,,,Name8,45,85,85,85,96 i changed my code a bit modified the functions to espace blank spaces and not return null values in the data tables while (($row = fgetcsv($file_data, 1000, ",")) !== FALSE) { if ((string) $row[0] != '0' and empty($row[0])) { continue; } $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } But it doesn't work with the specified csv files i think the ajax call breaks and that's why nothing happens.However it works fine with csv files without blank spaces
  3. Hi all ! i have been trying to implement the CSV policy in my files. I have a bit of code that I am not sure how I can change it to suit the policy. Here's the code snippet : if(isset($_SESSION['msg'])) { // The script below shows the sliding panel on page load $script = ' <script type="text/javascript"> $(function(){ $("div#panel").show(); $("#toggle a").toggle(); }); </script>'; } As can be seen the script is loaded conditionally here. So how can I remove javascript embedded from this code so that this may be compatible with the CSV policy. NOTE: the javascript functions are in a separate js file loaded in the header. Thanks all !
  4. I have multiple CSV files (example file.csv) that need to be read, and the data needs to be compared to the data in another csv file (data.csv) by an ID key which is in the first column of the file There are multiple rows and columns with data. First rows of the file is header column info so the first row needs to be skipped the data which is in the selected row of the file (file.csv) needs to be compared to data in data.csv by the ID key when the same ID key is found in a row, the data needs to be appended to the end of the row of that same ID key row in data.csv (everything except the ID key is copied to file.csv) CSV files are delimited by ; data is UTF-8 - Croatian I've made a script to parse through a file (data.csv) and print it but ain't that good with working multiple files and arrays to make it check the data from file.csv and append it...help? <?php $row = 1; if (($xxa = fopen("data.csv", "r")) !== FALSE) { echo "<meta charset=\"UTF-8\">"; while (($data = fgetcsv($xxa, 1000, ";")) !== FALSE) { if ($row==1) { $row++; continue; } $num = count($data); echo "<p>$row. <i>red: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "</br>\n"; } } fclose($xxa); } ?> ----- I've googled and found this other script online (other.php) which is awesome because it puts all the data in arrays but I have no idea how to select that first cell with an ID key in one file, and copy that row and append it to another csv file at the end of that ID key row :/ <?php /** * Convert a comma separated file into an associated array. * The first row should contain the array keys. * * Example: * * @param string $filename Path to the CSV file * @param string $delimiter The separator used in the file * @return array * @link http://gist.github.com/385876 * @author Jay Williams <http://myd3.com/> * @copyright Copyright (c) 2010, Jay Williams * @license http://www.opensource.org/licenses/mit-license.php MIT License */ function csv_to_array($filename='', $delimiter=',') { if(!file_exists($filename) || !is_readable($filename)) return FALSE; $header = NULL; $data = array(); if (($handle = fopen($filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { if(!$header) $header = $row; else $data[] = array_combine($header, $row); } fclose($handle); } return $data; } /** * Example */ print_r(csv_to_array('example.csv')); ?>
  5. Hi all, PHP newbie here. I've been trying to integrate Gravity Forms with Gravity View's Import Entries from CSV plugin. Unfortunately, it needs a bit of tweaking to get everything connected properly. I used a code snippet from David at Gravity Whiz, (HERE) that gets integrated into my Wordpress site's functions.php file, and have been trying to customize to to suit my needs. From what I understand in looking at the code, the only bit I need to tweak (I think) is the bottom portion: # Configuration new GW_Value_Exists_Validation( array( 'target_form_id' => 1, 'target_field_id' => 3, 'source_form_id' => '/RSVPcodes.csv', 'source_field_id' => 'rsvp', 'validation_message' => 'Hey! Don\'t be a villain! Provide a legit RSVP code to reserve your spot at the Smackdown.' ) ); My main question here: how to get the validation code to see the database that I've uploaded via the Import Entries plugin? I know ignorance is making me miss something that should be pretty simple. Right now, I've got it to validate a test word that I know is not in my database, and also a code that I know is in the database. It's coming back with both items as not valid. The end result will be a RSVP form that will be used to accept RSVPs only from people who have an RSVP code from their invitation, a lot like a license key validation system. The live site (and form I'm trying to tweak) is HERE. Thanks in advance for any help.
  6. Hello yes so I let myself be carried away, and then came a new small challenge. In the graph code is the csv file opened and soteret with a "explod" function. and it work fine as long as I only have one column with y data and one with x data. but when I start to get more column's it does not work. I've created a short example below. <?php define("LOG_FILE", "./data/test111/test111-2015-01-17.csv"); $times = array(); $values = array(); $values_test1 = array(); $file_lines = file(LOG_FILE , FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); foreach($file_lines as $line_num => $line_value) { $line_elements = explode(",", $line_value); $times[] = date($line_elements[0]); $values[] = $line_elements[1]; $values_test1[] = $line_elements[2]; } echo $values[2]; ?> the control echo I make "echo $values[2];" works fine, there is be the expected value. but if I try to "echo $values_test1[2];" so there is nothing. the CSV file looks like this. Date,temp1,temp2 2015-01-23-12-00,54,59 2015-01-23-12-01,54,59 2015-01-23-12-02,54,59 2015-01-23-12-03,54,58 2015-01-23-12-04,54,58 2015-01-23-12-05,54,58 2015-01-23-12-06,54,58 2015-01-23-12-07,54,58 2015-01-23-12-08,54,58 2015-01-23-12-09,54,58 2015-01-23-12-10,54,58 2015-01-23-12-11,53,58 2015-01-23-12-12,53,58 2015-01-23-12-13,53,58 2015-01-23-12-14,53,58 why can I not get the temp2 values into $ values_test1 [] thank you very much
  7. Hi Ive currently developed a script that connects via an API to send a message, and tested it with one user and it works perfectly. But now im bit stuck to send it to multiple users. All my visitors unique IDs are being stored into a file called unique.csv all in 1 column under each other. But what im currently trying to do is to recall the info from the csv and make a contact list to broadcast the message to. The csv file looks like: Here is my current script <?php $f_pointer=fopen("unique.csv","r"); // file pointer while(! feof($f_pointer)){ $ar=fgetcsv($f_pointer); } require_once ('MxitAPI.php'); /* Instantiate the Mxit API */ $key = '****'; $secret = '*****'; $visitor = '****'; $api = new MxitAPI($key, $secret); $api->get_app_token('message/send'); $api->send_message('guniverse', '$ar[0]', '*test message*', 'true'); echo 'Success'; ?>
  8. i want a situation where, when i upload something into my database, it creates a new table, everytime, i saw this $forum = "CREATE TABLE IF NOT EXISTS for_".$id." ( `id` int(11) NOT NULL AUTO_INCREMENT, `stud` int(11) DEFAULT NULL, `course` int(11) DEFAULT NULL, `message` varchar(1000) DEFAULT NULL, PRIMARY KEY (`id`) ) "; but don't know how to implement it into this query $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')";
  9. when i input this code it only uploads a single column into my database <html> <head> <title>MySQL file upload example</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html>
  10. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Import a CSV File with PHP & MySQL</title> </head> <body> <form action="" method="post" enctype="multipart/form-data" name="csv" id="csv"> Choose your file: <br /> <input name="csv" type="file" id="csv" /> <input type="submit" name="Submit" value="Submit" /> </form> </body> but i keep having this error Notice: Undefined index: csv in C:\wamp\www\youngsoul\upload\file.php on line 7
  11. Hi I have a script which picks up CSV files and inserts into a table (mysql). I am a beginner and finding it difficult to get the script to add an additional column to existing CSV, and add value to column, for each row... Here is the script.... How can I manipulate $csv and add a column (including separator) and value ($filedate) for each row? Help much appreciated. for example: CSV contains: Number, Name, LastName 1, John, Thomas 2, Jeffrey, James I need to add: Number, Name, LastName, Date 1, John, Thomas, 2014-10-31 2, Jeffrey, James, 2014-10-31 <?php #! /usr/bin/env php $databasehost = "localhost"; $databasename = "****"; $databasetable = "****"; $databaseusername="****"; $databasepassword = "****"; $fieldseparator = ","; $lineseparator = "\n"; $files = glob("*ETF_*.csv"); $filedate = "2014-10-31"; if (empty($files)) { die("No records were loaded."); } else foreach($files as $csv) $etf_array = array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); { try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, $etf_array ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csv)." INTO TABLE `$databasetable` FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES"); echo "Daily - Loaded a total of $affectedRows records from $csv.\n"; } ?>
  12. I'm trying to after submission 1. create a csv 2. insert record into db 3. send email that's created in form submission - $msg. 4. send email with attachment to only the email I specify (if possible) if not attach it to the email that's created at submission. I've search and search and found different methods but doesn't work with my code. I kept 3 lines at the top but can't get them to work ... either I don't get an email after submission or don't get an attachement. Can some one help? <?php $random_hash = md5(date('r', time())); $csvString = "..."; // your entire csv as a string $attachment = chunk_split(base64_encode($csvString)); $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { "First Name Required"; } if(empty($_POST['lastName'])) { "Last Name Required"; } if(empty($error)) { $to = "$to"; $subject = 'The Form'; $headers = "MIME-Version: 1.0 \r\n"; $headers .= "Content-Type: text/html; \r\n" ; $msg .="<html> <head></head> <body> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td>This is the email sent.</td></tr> </table> </body> </html>"; include('con.php'); $con = mysqli_connect($host,$user,$pass,$dbName); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"thetable"); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'"; $result = mysqli_query($con,$sql); if(($result->num_rows)>= 1) { $theerror = "You exist"; } else { $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'"; $success = "Sent ... Insert it!!!"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } $result = @mail($to, $subject, $msg, $headers); } mysqli_close($con); { } } } ?>
  13. Hi guys, What I'm trying to accomplish sounds like fairly easy task but due to my poor knowledge of php this turned to be quite a challenge. What I'm trying to do is to make a php script that will search the keywords on the multiple websites. Websites that I will search are all web shops, selling spare part for home appliances and keywords used are usually original spare part codes. When searching, script is searching these websites using their own search functions and not Google or other search engines. Input for this script should be a CSV file containing list of keywords and URLs of the web shops that needs to be search for all these keywords. Here is the example: http://prntscr.com/4ebhxh Script should perform like this: It picks up the 1st keyword, browse to the URL1, uses its search, searches for the product, if it finds it, copy its price and write it back to original input CSV. If it doesn't find match (search results appear empty) it should write "no match found" and continue to URL2, URL3 and so on... When all URLs from the list are checked for the 1st keyword, scripts picks up 2nd keyword and continues on through all these keywords are not checked. This would be a resulting CSV file after the 1st keyword is checked: http://prntscr.com/4ebj52 After all data from the input CSV file are processed, script should prompt a msg and create a download link for that CSV file to be downloaded. If there are multiple matches, in other words if for one keyword some of the website searches find 2 or more products, something like "More then one match" should be written in the file. Example: http://prntscr.com/4ebkcx Please note that non of the website is using SSL and non of them requires login in order to display the prizes. This fact should make this script easier to build. Its not important for this script to run fast (its better I think to run it with some timeouts because of the server glitches and bottlenecks). What is more important is to make it automatic so one can start it over the night, over the weekends. Number of the URLs would be around 10, and list of keywords from few tens, to a few hundred. If I can provide some additional clarification and info I'm available. Of course I would be willing to pay someone to help me accomplish this task. Cheers Dean
  14. Hello, I am trying to import a CSV file into an existing mysql table but it doesn't seem to work well. Here is how my mysql is looking like: 1 a_id int(11) AUTO_INCREMENT 2 a_lobecoid int(7) 3 a_code varchar(30) utf8_general_ci 4 a_omschint varchar(60) utf8_general_ci 5 a_beveiligingniv int(5) 6 a_type varchar(5) utf8_general_ci 7 a_assortiment int(5) 8 a_discipline varchar(30) utf8_general_ci 9 a_brutoprijs varchar(50) utf8_general_ci 10 a_status varchar(5) utf8_general_ci 11 a_levcode varchar(10) utf8_general_ci 12 a_omschr_nl varchar(60) utf8_general_ci 13 a_omschr_fr varchar(60) utf8_general_ci these are some lines from my CSV file 16158|-H|Factory installed heater|10|S|400|CCTV|45.0|E| 1829|Factory installed heater|Factory installed heater 16159|-IR|Factory installed IR LED ring|10|S|400|CCTV|50.0|E| 1829|Factory installed IR LED ring|Factory installed IR LED ring 9001|00-SBN2|Smoke box niet geaspireerd,230VAC|10|S|267|BRAND|1587.03|D| 642|Smoke box niet geaspireerd,230VAC|Smoke box pas aspiré,230VCA 9003|00-TP1|Telescopische verlengstok voor Smoke box,2,4-4,6m|10|S|267|BRAND|644.09000000000003|D| 642|Telescopische verlengstok voor Smoke box,2,4-4,6m|Rallonge téléscopique pour Smoke box,2,4-4,6m 9004|00-TP2|Telescopische verlengstok voor Smoke box,2,4-9,2m|10|S|267|BRAND|944.64999999999998|D| 642|Telescopische verlengstok voor Smoke box,2,4-9,2m|Rallonge téléscopique pour Smoke box,2,4-9,2m 12161|001-0081|Thermistor probe,rood, high temp. 0-+150°C|10|S|52|INBRAAK|136.91|D| 1731|Thermistor probe,rood, high temp. 0-+150°C|Sonde température,rouge,high temp. 0-+150°C Here you have the code for the import: $upload_article_query = "LOAD DATA INFILE 'ARTIKELS.CSV' INTO TABLE artikelen FIELDS TERMINATED BY '|' LINES TERMINATED BY '\\r\\n' (a_lobecoid, a_code, a_omschint, a_beveiligingniv, a_type, a_assortiment, a_discipline, a_brutoprijs, a_status, a_levcode, a_omschr_nl, a_omschr_fr)"; $upload_article_stmt = $dbh->prepare($upload_article_query); $upload_article_stmt->execute(); If i use the code then in the MYSQL table the first line is filled in but where the second line has to start it just writes it into the last column and doesn't start a new line. Also if i edit that first line it shows a lot of "?" (questionmarks) into a window symbol. Anyone has an idea what i am doing wrong? In attachment some printscreens of my table after the insert. Apologies for the Dutch language. Thanks in advance
  15. 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); } ?>
  16. Hi, I have a problem deleting duplicate rows in a .csv file. I have posted on another forum, but with no useful help, the file is still saving the row of .csv even in I write in a duplicate mobile number. The record file is only 2000 lines long and performance is not an issue. Please help, as it is time-sensitive. Cheers <?php $filename = "input.csv"; $csv_output .= "\n";$title=$_GET[title];$fname=$_GET[fname]; $sname=$_GET[sname];$notes=$_GET[notes];$mobile=$_GET[mobile]; $string="$title,$fname,$sname,$mobile,$notes,$csv_output"; $file = fopen($filename, "c"); flock($file, LOCK_EX); $stat = fstat($file) if($stat['size'] == 0) { // file created for the first time fwrite($file, "Title,First Name,Last Name,MobileNumber,Notes\n$string"); flock($file, LOCK_UN); fclose($file); return; } while (($buffer = fgets($file, 2188)) !== false) { if(!stripos($buffer, $mobile) { $somecontent .= $buffer; } else { flock($file, LOCK_UN); fclose($file); return; } } // Otherwise fwrite() the line else { fwrite($file, $string); } flock($file, LOCK_UN);fclose($file); ?>
  17. Hi, I have a list of products in CSV format, but I need to following to take place: I need PHP to read CSV file and compare it with a previous CSV file For product additions, generate a new CSV file with just new items called "Additions.CSV" For product deletions, generate a new CSV file with just deleted products called "Deleted.CSV" Any guidance would be appreciated. Thanks!
  18. Hi, I have a csv-file with data like this: I have a mysql database with all the names of the ingredients and a webpage with a searchbox so for example if i search for apple select it and then i search and select blueberry i want to get the corresponding data for apple and blueberry ( -4 in the example ). I know i can read the csv-file with 'fgetcsv' but i'm not sure how to import it into an array so it's easy to use so i can search for ingredients. Does anybody have an idea how to do this in php?
  19. I am trying to read a large number of products, from a CSV file. I am attempting to parse each line and produce item lists, each with a Make, Model and set of OEM numbers. Multiple models use the same set of OEM values. Here is a sample screenshot of my product spreadsheet. - http://prntscr.com/3aorwh Here is my code below. Underneath will be my CSV contents (only a sample) error_reporting(0); $file = fopen("new.csv","r"); $makeArray = array(); $make = ''; $model = 0; $specificModel = ''; while(! feof($file)) { $lineVal = fgetcsv($file, 0, '@'); // Adds in 'Make' to initial makeArray array if ( isset($lineVal[0]) && empty( $lineVal[1] ) && empty( $lineVal[2] ) ) { $make = $lineVal[0]; $makeArray[$make] = array(); } // Gets Model lists if ($lineVal[1] !== '') { $model++; $makeArray[$make][$model] = array(); $specificModel = explode(",", $lineVal[1]); foreach($specificModel as $t) { $makeArray[$make][$model][$t] = array(); } } $OEMs = explode(',', $lineVal[2]); foreach($makeArray[$make][$model] as $specific) { if ($specific !== '') { // This loop adds in the variables foreach($OEMs as $oem){ $makeArray[$make][$model][$t][$oem] = array(); } } } } // Echo results echo '<pre>'; var_dump($makeArray) . '<br />'; echo '</pre>'; fclose($file); Here is the CSV content: Brother@@ Brother TN12K Compatible Black Toner Cartridge@HL-4200 Series@TN12BK Brother TN12C Compatible Cyan Toner Cartridge@@TN12C Brother TN12M Compatible Magenta Toner Cartridge@@TN12M Brother TN12Y Compatible Yellow Toner Cartridge@@TN12Y Brother TN04K Compatible Black Toner Cartridge, For HL-2700,@HL-2700CN,MFC-9420CN@TN04BK Brother TN04C Compatible Cyan Toner Cartridge, For HL-2700,@@TN04C Brother TN04M Compatible Magenta Toner Cartridge@@TN04M Brother TN04Y Compatible Yellow Toner Cartridge@@TN04Y When I output my code, the following structure occurs. Please note at this point, the OEM values are grouped, and each model within the dark borders on the left, has to have ALL of the values on the right side within these borders. Output array(1) { ["Brother"]=> array(2) { [1]=> array(1) { ["HL-4200 Series"]=> array(4) { ["TN12BK"]=> array(0) { } ["TN12C"]=> array(0) { } ["TN12M"]=> array(0) { } ["TN12Y"]=> array(0) { } } } [2]=> array(2) { ["HL-2700CN"]=> array(0) { } [" MFC-9420CN"]=> array(4) { ["TN04BK"]=> array(0) { } ["TN04C"]=> array(0) { } ["TN04M"]=> array(0) { } ["TN04Y "]=> array(0) { } } } } } Any takers as to why HL-2700CN and MFC-9420CN (or any sections like this) do not ALL get assigned the respective grouped OEMs? Additional information: The format of the end result needs to look like: Brother HL-4200 Series TN12BK TN12C TN12M TN12Y HL-2700CN TN04BK TN04C TN04M TN04Y MFC-9420CN TN04BK TN04C TN04M TN04Y Thanks
  20. Hello ! I'm new on this board and I need your help ! I explain you my problem. I'd like to collect the content of around 1000 URL in a textfile (I use the wget function in a bash). And then I want to parse this textfile in order to pick one type of content up in a csv file. 1) So my bash is this one : file=/home/julien/tests/file.txt for i in $(cat $file) do wget $i -O ->> songs_t.txt; done It works perfectly and the textfile songs_t.txt is well created. That textfile contains the content of the 1000 URLs. 2) Then I make a php script to parse songs_t.txt. I only want to get concert setlists (the setlist is only a part of a the content of each URL). So my approach is to remove tags such as 'a', 'h4', 'Title' and so on and save the rest in a csv file called 'SONGS.csv' An example of a URL can be seen here : http://members.tripod.com/~fun_fun_fun/8-17-63.html My part of the php script dealing with the parsing is this one : $html = file_get_html('songs_t.txt'); foreach ($html->find('title, script, div, center, style, img, noscript, h4, a') as $es) $es->outertext = 'title, script, div, center, style, img, noscript, h4, a'; $f = fopen('SONGS.csv', "w"); fwrite ($f, $html); fclose($f); The script works for the 35 first URL (I nearly only get the setlists) but as soon as the script has to deal with more than 35 URL, I have the following error message : Call to a member function find() on a non-object in /home/julien/tests/boys2.php on line 23. That line 23 corresponds to : foreach ($html->find('title, script, div, center, style, img, noscript, h4, a') as $es) 3) In order to test if my html object is valid, I use that code : html = file_get_html('songs_t.txt'); if (!is_object($html)){ echo "invalid object"; } And the result is "invalid object". This test is made in a textfile composed of the content of 50 URL. But when I apply that test on textfile composed of 30 URL, I have no error ! So how can I do to parse my HTML even if it's not a entire valid object ? Could you help me please ? Thanks !
  21. I want to do a daily auto update from a CSV that's being placed via FTP heres how the structure looks: My program: Domain->Subdomain->files Target CSV: Domain->FTPDir->.csv Is there anyway to access this file without having to open up an ftp connection every time? Also I know what time the file is placed everyday. Is there something I can set up to auto run the update script everyday at that time or even set up an event listener to know when the file has been placed?
  22. I have some code that I edited for importing csv into mysql using PDO to bind parameters. I thought it was working before, but tested it again and the issue I have is that only one line (the fourth line) of the csv file is getting imported. The first line is the header which are the table field names. The first method below is what's used to parse the csv files and bind the field names with the data. The second method, loops through. I need another pair of eyes, so if anyone can help me figure out my issue, I would greatly appreciated. public function getSQLinsertsArray($sqlTable) { $data = $this->getCSVarray(); $queries = []; $fieldsStr = ""; while(list($k, $field) = each($data)) { if(empty($fieldStr)) $fieldStr = implode(", ", array_keys($field)); //$valueStr = "'".implode("', '", $field)."'"; $placeholders = array_map(function($col) { return ":$col"; }, $field); $bind = array_combine($placeholders,$field); $queries[] = DB::inst()->query("INSERT INTO ".$sqlTable." (".$fieldStr.") VALUES (".implode(",", $placeholders).");",$bind); //error_log(var_export($queries,true)); } return $queries; } public function queryInto($sqlTable) { $queries = $this->getSQLinsertsArray($sqlTable); while(list($k, $query) = each($queries)) { $q = $query; } if($q > 0) { return true; } else { return false; } }
  23. I have a csv file which contains this data: person1,person2,person3 first,john,steve,mike last,doe,whinney,speirs I want to create an xml file which looks like this: <root> <person1> <first> john </first> <last> doe </last> </person1> <person2> <first> steve </first> <last> whinney </last> </person2> <person3> <first> mike </first> <last> speirs </last> </person3> </root> Thanks
  24. Background: I work on an application that tracks server information. The data comes from 10 tables in a database that are exact replicas of 10 CSV files that insert daily into their specific tables. The database is nowhere near normalized and is a straight dump from the CSV to the db tables. (CSV headers match the table fields) Problem: I need to figure out a way to get the data from the CSV data into a normalized database for the application to read instead of a straight dump of the CSV data to the table. I have little control over the CSV's, but do have control over what happens with them afterwards. What would be the best way to get logical data into a normalized database from a set of CSV's? Thanks!
  25. Hi there, I'm struggling a bit with this. This works fine: line 99: preg_match('^\s', $xmlElem) However, I shouldn't be writing the pattern there directly, because the pattern is in a tab-separated file. If I get it with fgetcsv and put it in another variable $pattern = $data[0]; echo $pattern; // outputs ^\s and then use that variable in the above match line 99: preg_match('/'. $pattern .'/', $xmlElem) then I get an error like: and there's no match. Could anyone help me out? Thank you so much! Cheers, Manuel
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.