I'm a beginner so sorry if my question is inappropriate.
I'm trying to create a function that allows me to load and display a csv file in PHP, but it keeps giving me an error.
Here is the function:
<?php
function load_csv_file($nom){
$tableau_asso= array();
$fichier = fopen($nom, "r");
while($ligne = fgetcsv($fichier, 1024, ';')){
array_push($tableau_asso, $ligne);
}
fclose($fichier);
foreach($tableau_asso as $ligne){
print($ligne[0]);
print(", ");
print($ligne[1]);
print("<br>");
}
return $tableau_asso;
}
?>
Then I created another document where I call this function:
<?php
include("library.php");
$nom = 'C:\\MAMP\\htdocs\\MEDAS-PHP\\data.csv';
$mon_tableau = load_csv_file($nom);
?>
When I try to load it, nothing happens. What am I doing wrong?
Related
I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>
Is this possible to store other php code inside a variable.
I am trying to create php page from backend as same in CMS
$var = include 'page.php' . "
php code start
$code = include 'bootstrap.php' . "
// header code
php code
}
// footer code
";
$menu_alias = "newHTMLFileName";
$path= "../folder".$menu_alias.".php";
if (!file_exists ($path))
{
$handle = fopen ($path, "w");
$write = fwrite ($handle, $code);
fclose($handle);
echo "created";
}
else
{
echo "already created";
}
I want to know if it is this possible to write PHP code and MySQL query and store both to a variable.
Thanks in advance
I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php
This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I have the following codes and they are not working:
index.php:
include("loadData.php");
$my_var = loadData("myTxt.txt");
var_dump($my_var);
loadData.php:
function loadData($my_file){
if(file_exists($my_file)){
$file_contents = file_get_contents($my_file);
$file_contents = json_decode($file_contents);
}else{
// If file doesn't exist, creates the file and runs the function again
$data_to_insert_into_file = simplexml_load_file("http://site_with_content.com");
$fp = fopen($my_file, "w");
fwrite($fp, json_encode($data_to_insert_into_file));
fclose($fp);
// Since the file is created I will call the function again
loadData($my_file);
return;
}
// Do things with the decoded file contents (this is suposed to run after the file is loaded)
$result = array();
$result = $file_contents['something'];
return $result;
}
This works as expected in the second time (after the file is created), I can display info on index.php, but in the first time I run (before the file is created) it always displays $result as NULL, I can't understand why since I call the function again...
Any idea?
Thank you
You don't return anything when you do your fetch:
if (...) {
$file_contents = file_get_contents(...);
// no return call here
} else {
...
return; // return nothing, e.g. null
}
return $result; // $result is NEVER set in your code
You should have return $file_contents. Or better yet:
if (...) {
$result = get cached data
} else {
$result = fetch/get new data
}
return $result;
by using the proper variable names everywhere.
Is there any alternative to file_get_contents that would create the file if it did not exist. I am basically looking for a one line command. I am using it to count download stats for a program. I use this PHP code in the pre-download page:
Download #: <?php $hits = file_get_contents("downloads.txt"); echo $hits; ?>
and then in the download page, I have this.
<?php
function countdownload($filename) {
if (file_exists($filename)) {
$count = file_get_contents($filename);
$handle = fopen($filename, "w") or die("can't open file");
$count = $count + 1;
} else {
$handle = fopen($filename, "w") or die("can't open file");
$count = 0;
}
fwrite($handle, $count);
fclose($handle);
}
$DownloadName = 'SRO.exe';
$Version = '1';
$NameVersion = $DownloadName . $Version;
$Cookie = isset($_COOKIE[str_replace('.', '_', $NameVersion)]);
if (!$Cookie) {
countdownload("unqiue_downloads.txt");
countdownload("unique_total_downloads.txt");
} else {
countdownload("downloads.txt");
countdownload("total_download.txt");
}
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$DownloadName.'" />';
?>
Naturally though, the user accesses the pre-download page first, so its not created yet. I do not want to add any functions to the pre download page, i want it to be plain and simple and not alot of adding/changing.
Edit:
Something like this would work, but its not working for me?
$count = (file_exists($filename))? file_get_contents($filename) : 0; echo $count;
Download #: <?php
$hits = '';
$filename = "downloads.txt";
if (file_exists($filename)) {
$hits = file_get_contents($filename);
} else {
file_put_contents($filename, '');
}
echo $hits;
?>
you can also use fopen() with 'w+' mode:
Download #: <?php
$hits = 0;
$filename = "downloads.txt";
$h = fopen($filename,'w+');
if (file_exists($filename)) {
$hits = intval(fread($h, filesize($filename)));
}
fclose($h);
echo $hits;
?>
Type juggling like this can lead to crazy, unforeseen problems later. to turn a string to an integer, you can just add the integer 0 to any string.
For example:
$f = file_get_contents('file.php');
$f = $f + 0;
echo is_int($f); //will return 1 for true
however, i second the use of a database instead of a text file for this. there's a few ways to go about it. one way is to insert a unique string into a table called 'download_count' every time someone downloads the file. the query is as easy as "insert into download_count $randomValue" - make sure the index is unique. then, just count the number of rows in this table when you need the count. the number of rows is the download count. and you have a real integer instead of a string pretending to be an integer. or make a field in your 'download file' table that has a download count integer. each file should be in a database with an id anyway. when someone downloads the file, pull that number from the database in your download function, put it into a variable, increment, update table and show it on the client however you want. use PHP with jQuery Ajax to update it asynchronously to make it cool.
i would still use php and jquery.load(file.php) if you insist on using a text file. that way, you can use your text file for storing any kind of data and just load the specific part of the text file using context selectors. the file.php accepts the $_GET request, loads the right portion of the file and reads the number stored in the file. it then increments the number stored in the file, updates the file and sends data back to the client to be displayed any way you want. for example, you can have a div in your text file with an id set to 'downloadcount' and a div with an id for any other data you want to store in this file. when you load file.php, you just send div#download_count along with the filename and it will only load the value stored in that div. this is a killer way to use php and jquery for cool and easy Ajax/data driven apps. not to turn this into a jquery thread, but this is as simple as it gets.
You can use more concise equivalent yours function countdownload:
function countdownload($filename) {
if (file_exists($filename)) {
file_put_contents($filename, 0);
} else {
file_put_contents($filename, file_get_contents($filename) + 1);
}
}