Hoe in een bestand in PHP in te schrijven?

Ik heb dit script op een gratis PHP-ondersteunende server:

<html>
<body>
<?php
$file = fopen("lidn.txt","a");
fclose($file);
?>
</body>
</html>

Het creëert het bestand lidn.txt, maar het is leeg.

Hoe kan ik een bestand maken en er iets in schrijven,
Bijvoorbeeld de lijn “Cats Chase Mice”?


1, Autoriteit 100%

U kunt een functie op een hoger niveau gebruiken zoals:

file_put_contents($filename, $content);

die identiek is aan het bellen van fopen () , fwrite () , en Fclose () achtereenvolgens om gegevens naar een bestand te schrijven.

Documenten: file_put_contenten


2, Autoriteit 52%

Overweeg fwrite () :

<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

3, Autoriteit 14%

$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);

http://php.net/manual/en/function.fwrite.php


4, Autoriteit 7%

$text = "Cats chase mice";
$filename = "somefile.txt";
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);

U gebruikt fwrite()


Antwoord 5, autoriteit 6%

Het is gemakkelijk om een bestand te schrijven:

$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);

Antwoord 6, autoriteit 4%

Dit zijn de stappen:

  1. Open het bestand
  2. Schrijf naar het bestand
  3. Sluit het bestand

    $select = "data what we trying to store in a file";
    $file = fopen("/var/www/htdocs/folder/test.txt", "w");        
    fwrite($file, $select->__toString());
    fclose($file);
    

Antwoord 7, autoriteit 4%

Om naar een bestand te schrijven in PHPmoet je de volgende stappen doorlopen:

  1. Open het bestand

  2. Schrijf naar het bestand

  3. Sluit het bestand

    $select = "data what we trying to store in a file";
    $file = fopen("/var/www/htdocs/folder/test.txt", "a");
    fwrite($file  , $select->__toString());
         fclose($file );
    

Antwoord 8, autoriteit 4%

Ik gebruik de volgende code om bestanden naar mijn webdirectory te schrijven.

write_file.html

<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>

write_file.php

<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
    echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
    $file = fopen("demo.php", "w");
    echo fwrite($file, $cd);
    // show a success msg 
    echo "data successfully entered";
    fclose($file);
}
?>

Dit is een werkend script. Zorg ervoor dat u de URL in het formulieractie en het doelbestand in fopen()-functie wijzigen als u het op uw site wilt gebruiken.

Other episodes