PHP Write Posted Data to File - php

I'm relatively new to PHP and I'm trying to get a small script running. I have a VB .net program that posts data using the following function.
Public Sub PHPPost(ByVal User As String, ByVal Score As String)
Dim postData As String = "user=" & User & "&" & "score=" & Score
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://myphpscript"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.ContentLength = byteData.Length
Dim postReqStream As Stream = postReq.GetRequestStream()
postReqStream.Write(byteData, 0, byteData.Length)
postReqStream.Close()
End Sub
Where "myphpscript" is acutally the full URL to the PHP script. Basically I'm trying to POST the "User" variable and the "Score" variable to the PHP script. The script I've tried is as follows:
<?php
$File = "scores.rtf";
$f = fopen($File,'a');
$name = $_POST["name"];
$score = $_POST["score"];
fwrite($f,"\n$name $score");
fclose($f);
?>
The "scores.rtf" does not change. Any help would be appreciated. Thanks ahead of time, I'm new to PHP.

Ensure that your script is receiving the POST variables.
http://php.net/manual/en/function.file-put-contents.php
You can try file_put_contents, it combines the use of fopen ,fwrite & fclose.
It could be wise to use something like isset/empty to check that there is something to write before writing.
<?php
$file = 'scores.rtf';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= print_r($_POST);
//Once confirmed remove the above line and use below
$current .= $_POST['name'] . ' ' . $_POST['score'] . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Also, totally overlooked the RTF part, definitely look into what Mahan mentioned. I'd suggest the above if you have no need for that specific file type.

The "scores.rtf" does not change.
well RTF files is handled differently because its not really a pure text file it contains meta-data and tags that controls how text is displayed on the rtf file. please have a time to read to the following sources
http://www.webdev-tuts.com/generate-rtf-file-using-php.html
http://b-l-w.de/phprtf_en.php
http://paggard.com/projects/doc.generator/doc_generator_help.html
if in any case you want a normal text file you can use the code below, don't use fwrite(), please use file_put_contents()
file_put_contents("scores.txt", "\n$name $score");

Related

Read and replace contents in .docx (Word) file

I need to replace content in some word documents based on User input. I am trying to read a template file (e.g. "template.docx"), and replace First name {fname}, Address {address} etc.
template.docx:
To,
The Office,
{officeaddress}
Sub: Authorization Letter
Sir / Madam,
I/We hereby authorize to {Ename} whose signature is attested here below, to submit application and collect Residential permit for {name}
Kindly allow him to support our International assignee
{name} {Ename}
Is there a way to do the same in Laravel 5.3?
I am trying to do with phpword, but I can only see code to write new word files - but not read and replace existing ones. Also, when I simply read and write, the formatting is messed up.
Code:
$file = public_path('template.docx');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($file);
$phpWord->save('b.docx');
b.docx
To,
The Office,
{officeaddress}
Sub:
Authorization Letter
Sir / Madam,
I/We hereby authorize
to
{Ename}
whose signature is attested here below, to submit a
pplication and collect Residential permit
for
{name}
Kindly allow him to support our International assignee
{name}
{
E
name}
This is the working version to #addweb-solution-pvt-ltd 's answer.
//This is the main document in Template.docx file.
$file = public_path('template.docx');
$phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);
$phpword->setValue('{name}','Santosh');
$phpword->setValue('{lastname}','Achari');
$phpword->setValue('{officeAddress}','Yahoo');
$phpword->saveAs('edited.docx');
However, not all of the {name} fields are changing. Not sure why.
Alternatively:
// Creating the new document...
$zip = new \PhpOffice\PhpWord\Shared\ZipArchive();
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$file = public_path('template.docx');
$temp_file = storage_path('/app/'.date('Ymdhis').'.docx');
copy($template,$temp_file);
if ($zip->open($temp_file) === TRUE) {
//Read contents into memory
$oldContents = $zip->getFromName($fileToModify);
echo $oldContents;
//Modify contents:
$newContents = str_replace('{officeaddqress}', 'Yahoo \n World', $oldContents);
$newContents = str_replace('{name}', 'Santosh Achari', $newContents);
//Delete the old...
$zip->deleteName($fileToModify);
//Write the new...
$zip->addFromString($fileToModify, $newContents);
//And write back to the filesystem.
$return =$zip->close();
If ($return==TRUE){
echo "Success!";
}
} else {
echo 'failed';
}
Works well. Still trying to figure how to save it as a new file and force a download.
I have same task to edit .doc or .docx file in php, i have use this code for it.
Reference : http://www.onlinecode.org/update-docx-file-using-php/
$full_path = 'template.docx';
//Copy the Template file to the Result Directory
copy($template_file_name, $full_path);
// add calss Zip Archive
$zip_val = new ZipArchive;
//Docx file is nothing but a zip file. Open this Zip File
if($zip_val->open($full_path) == true)
{
// In the Open XML Wordprocessing format content is stored.
// In the document.xml file located in the word directory.
$key_file_name = 'word/document.xml';
$message = $zip_val->getFromName($key_file_name);
$timestamp = date('d-M-Y H:i:s');
// this data Replace the placeholders with actual values
$message = str_replace("{officeaddress}", "onlinecode org", $message);
$message = str_replace("{Ename}", "ingo#onlinecode.org", $message);
$message = str_replace("{name}", "www.onlinecode.org", $message);
//Replace the content with the new content created above.
$zip_val->addFromString($key_file_name, $message);
$zip_val->close();
}
To read and replace content from Doc file, you can use PHPWord package and download this package using composer command:
composer require phpoffice/phpword
As per version v0.12.1, you need to require the PHP Word Autoloader.php from src/PHPWord folder and register it
require_once 'src/PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
1) Open document
$template = new \PhpOffice\PhpWord\TemplateProcessor('YOURDOCPATH');
2) Replace string variables for single
$template->setValue('variableName', 'MyVariableValue');
3) Replace string variables for multi occurrence
- Clone your array placeholder to the count of your array
$template->cloneRow('arrayName', count($array));
- Replace variable value
for($number = 0; $number < count($array); $number++) {
$template->setValue('arrayName#'.($number+1), htmlspecialchars($array[$number], ENT_COMPAT, 'UTF-8'));
}
4) Save the changed document
$template->saveAs('PATHTOUPDATED.docx');
UPDATE
You can pass limit as third parameter into $template->setValue($search, $replace, $limit) to specifies how many matches should take place.
If you find simple solution you can use this library
Example:
This code will replace $search to $replace in $pathToDocx file
$docx = new IRebega\DocxReplacer($pathToDocx);
$docx->replaceText($search, $replace);
Library phpoffice/phpword working is ok.
For correct working you must use the right symbols in your Word document, like that:
${name}
${lastname}
${officeAddress}
and for method "setValue" you need to use only names, like:
'name'
'lastname'
'officeAddress'
Very good working within Laravel, Lumen, and other frameworks
Example:
//This is the main document in Template.docx file.
$file = public_path('template.docx');
$phpword = new \PhpOffice\PhpWord\TemplateProcessor($file);
$phpword->setValue('name','Santosh');
$phpword->setValue('lastname','Achari');
$phpword->setValue('officeAddress','Yahoo');
$phpword->saveAs('edited.docx');

How can I add variable names to the end of a file?

I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);

Writing to a file adds weird content at the end of the line

I am working on a program that parses text files uploaded by a user and then saves the parsed XML file on the server. However, when I write the XML file I get some the text
at the end of each line. This text is not in my original text file. I didn't even notice it until I opened the new XML file to verify that it was righting all of the content. Has anyone ran into this before and if so can you tell me if it's due to the way I'm creating and writing my file?
fileUpload.php - These 3 lines occur when the user uploads the file.
$fileName = basename($_FILES['fileaddress']['name']);
$fileContents = file_get_contents($_FILES['fileaddress']['tmp_name']);
$xml = $parser->parseUnformattedText($fileContents);
$parsedFileName = pathinfo($fileName, PATHINFO_FILENAME) . ".xml";
file_put_contents($parsedFileName, $xml);
parser.php
function parseUnformattedText($inputText, $bookName = "")
{
//create book, clause, text nodes
$book = new SimpleXmlElement("<book></book>");
$book->addAttribute("bookName", $bookName);
$conj = $book->addChild("conj", "X");
$clause = $book->addChild("clause");
$trimmedText = $this->trimNewLines($inputText);
$trimmedText = $this->trimSpaces($inputText);
$text = $clause->addChild("text", $trimmedText);
$this->addChapterVerse($text, "", "");
//make list of pconj's for beginning of file
$pconjs = $this->getPconjList();
//convert the xml to string
$xml = $book->asXml();
//combine the list of pconj's and xml string
$xml = "$pconjs\n$xml";
return $xml;
}
Input text file
1:1 X
it seemed good to me also,
X
having had perfect understanding of all things from the very first
to write you an orderly account, [most] excellent Theophilius
and
1:4
that
you may know the certainty of those things in which you were instructed
1:5 X
There was in the days of Herod, the king of Judea and a certain priest named Zacharias
X
his wife[was] of the daughters of Aaron
and
her name [was] Elizabeth.
1:8 So
it was,
that
while he was serving as priest 1:9 before God in the order of his division,
1:10 and
the whole multitude of the people was praying outside at the hour of incense
but
therefore
it was done.
Going off of Seroczynski's answer I was able to create a function that trimmed removed any carriage returns from the text. The XML output looked fine after that. Here's the function I used to fix the issue:
function trimCarriageReturns($text)
{
$textOut = str_replace("\r", "\n", $text);
$textOut = str_replace("\n\n", "\n", $textOut);
return $textOut;
}
is the ASCII character for \r\n which doesn't seem to come out correctly from parseUnformattedText().
Try $xml = nl2br($parser->parseUnformattedText($fileContents));

FLASH AS2 and PHP variables

My Flash movie reads and sends data to a PHP file in a free server. It seems ok for Flash to read variable values from a text file (which is managed by a PHP file) if they are wrote in this way: &variable = value&, I have no problem with that.
But my PHP file, pre-treated (by some mathematical functions) data sent by Flash and then, updates the values in the text file, that is my intention but I can't accomplish it.
Suppose I want to update a counter ( it counts how many times the data were updated):
in the text file I have &counter=0& (initial value) and if I put in the PHP file:
<?php
$fp = fopen("jose_stats.txt", "r");// I guess with it, I've read all the variables and values
// one of them is the variable &counter.
fclose($fp);
$toSave = "&counter=&counter+1&\n";
$fp = fopen("jose_stats.txt", "w");
if(fwrite($fp, "$toSave")) {
echo "&verify=success&"; //prints to screen &verify=success which flash will read
//and store as myVars.verify
} else { // simple if statement
echo "&verify=fail&"; //prints to screen &verify=fail which flash will read and
//store as myVars.verify
}
fclose($fp);
?>
but then, I check my text file and it has &counter=&counter+1& line :( and not the expected &counter =1&.
Please, give me and advise. Thank you.
Why not use JSON?
Just store the data in JSON format:
$count = 1;
$toWrite = array( 'count' => $count );//put other data into this array if you want
//encode it
$toWrite = json_encode( $toWrite );
//and now write the data
To decode it in flash, import the JSON class:
An example of JSON in as2 using the JSON.as class:
try {
var o:Object = JSON.parse(jsonStr);
var s:String = JSON.stringify(obj);
} catch(ex) {
trace(ex.name + ":" + ex.message + ":" + ex.at + ":" + ex.text);
}
So just import the class, and run JSON.parse( yourPhpResponse );.
Also, the reason for why you're seeing &counter=& in the text file is because you're storing it like that: $toSave = "&counter=&counter+1&\n";.

writing special characters to txt file

I am reading some data from a remote file, got every thing working till the point when i write some specific lines to a text file.
problem here is, when i write something like Girl's Goldtone 'X' CZ Ring it becomes Girl & apos;s Goldtone &apos ;X & apos; CZ Ring in txt file.
how do i write to txt file so that it retains text like written above and not show character code but actual character.
sample of my code.
$content_to_write = '<li class="category-top"><span class="top-span"><a class="category-top" href="'.$linktext.'.html">'.$productName.'</a></span></li>'."\r\n";
fwrite($fp, $content_to_write);
$linktext = "Girls-Goldtone-X-CZ-Ring";
$productName = "Girl's Goldtone 'X' CZ Ring";
var_dump
string '<li class="category-top"><span class="top-span"><a class="category-top" href="Stellar-Steed-Gallery-wrapped-Canvas-Art.html">&apos;Stellar Steed&apos; Gallery-wrapped Canvas Art</a></span></li>
' (length=195)
Code
$productName =$linktext;
$linktext = str_replace(" ", "-", $linktext);
$delChar = substr($linktext, -1);
if($delChar == '.')
{
$linktext = substr($linktext, 0, -1);
}
$linktext = removeRepeated($linktext);
$linktext = remove_invalid_char($linktext);
$productName = html_entity_decode($productName);
$content_to_write = '<li class="category-top"><span class="top-span"><a class="category-top" href="'.$linktext.'.html">'.$productName.'</a></span></li>'."\r\n";
var_dump($content_to_write);
fwrite($fp, utf8_encode($content_to_write));
Is it that you are reading the data from a remote file and then writing the same to a txt file? Agree with the above comment, its an issue with encoding. Try the following code:
$file = file_get_contents("messages.txt");
$file = mb_convert_encoding($file, 'HTML-ENTITIES', "UTF-8");
echo $file;
echo the response to your browser and see. If found proper, write the response to your txt file. Ensure that your txt file is UTF8 - encoded.
Check this out:: Write Special characters in a file.
fwrite is binary-safe, meaning it doesn't do any encoding stuff but just writes whatever you feed it directly to the file. It looks like the $productName variable you're writing is already entity-encoded before writing. Try running html_entity_decode over the variable first.
Note that html_entity_decode doesn't touch single quotes (&apos;) by default; you'll have to set the ENT_QUOTES flag in the second parameter. You might also want to explicitly specify an encoding in the third parameter.

Categories