My basic PHPWord setup is working.
This is my code:
<?php
require_once 'PhpWord/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
function getEndingNotes($writers)
{
$result = '';
// Do not show execution time for index
if (!IS_INDEX) {
$result .= date('H:i:s') . " Done writing file(s)" . EOL;
$result .= date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB" . EOL;
}
// Return
if (CLI) {
$result .= 'The results are stored in the "results" subdirectory.' . EOL;
} else {
if (!IS_INDEX) {
$types = array_values($writers);
$result .= '<p> </p>';
$result .= '<p>Results: ';
foreach ($types as $type) {
if (!is_null($type)) {
$resultFile = 'results/' . SCRIPT_FILENAME . '.' . $type;
if (file_exists($resultFile)) {
$result .= "<a href='{$resultFile}' class='btn btn-primary'>{$type}</a> ";
}
}
}
$result .= '</p>';
}
}
return $result;
}
// Template processor instance creation
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('template.docx');
// Variables on different parts of document
//$templateProcessor->setValue('vorname', htmlspecialchars('John')); // On section/content
//$templateProcessor->setValue('nachname', htmlspecialchars('Doe')); // On footer
//$templateProcessor->setValue('funktion', htmlspecialchars('Manager'));
// Simple table
$templateProcessor->cloneRow('rowValue', 10);
//clone our things
// Will clone everything between ${tag} and ${/tag}, the number of times. By default, 1.
$templateProcessor->cloneBlock('CLONEME', 5);
//delete things
// Everything between ${tag} and ${/tag}, will be deleted/erased.
$templateProcessor->deleteBlock('DELETEME');
// Saving the document as OOXML file...
$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
ob_clean();
$templateProcessor->saveAs($temp_file);
getEndingNotes(array('Word2007' => 'docx'));
header("Content-Disposition: attachment; filename='cv.docx'");
readfile($temp_file); // or echo file_get_contents($temp_file);
unlink($temp_file); // remove temp file
?>
it works well for this Word file.
However when I change something in my word file PHPWord delivers a corupted file. It has something to do with XML Errors. My question is, how can I edit my word file and get a perfectly working file without errors?
Is there a tool to fix XML?
I'm having the same issue and this is the first response through a Google search.
I've discovered that using a "deleteBlock()" function to remove an unneeded section will do something to the template that makes it unable to be opened with MS Word / Google Docs. I'm able to open with Mac Pages just fine, but for some reason the deleteBlock() function is doing something weird with the export.
My edit was instead of using a deleteBlock(), I did:
$templateProcessor->cloneBlock('HOBBYBLOCK', 0);
("Hobbies" was just the name of the section I was avoiding on case by case exports)
Effectively removing the {} block wrappers and
Setting the internal variable / injection point to nothing.
This seemed to resolve my issue. Just a heads up for anyone in the future who finds this and needs help troubleshooting. :^}
I found an answer, while editing the word file word inserts different xml elements between words. I had to edit the file manually in an editor making sure the replace values were not seperated by tags.
Related
I am working with wordpress -> contact form 7 and saving the data with contact form 7 to database extension plugin.
The plugin has filters to modify data before saving into database. ([Like This Page])1
now i wanted to save the file into different folder on the server and output link to that file into the admin panel. i used the filter like this.
function cfdbFilterSaveFile($formData) {
// CHANGE THIS: CF7 form name you want to manipulate
$formName = 'DemoReport';
// CHANGE THIS: upload field name on your form
$fieldName = 'Report';
// CHANGE THIS: directory where the file will be saved permanently
$uploaddir = '/home2/username/public_html/example.com/report/wp-content/uploads/reports/';
$urlDir = 'http://example.com/report/wp-content/uploads/reports/';
if ($formData && $formName == $formData->title && isset($formData->uploaded_files[$fieldName])) {
// make a copy of data from cf7
$formCopy = clone $formData;
// breakdown parts of uploaded file, to get basename
$path = pathinfo($formCopy->uploaded_files[$fieldName]);
// directory of the new file
$newfile = $uploaddir . $path['basename'];
// check if a file with the same name exists in the directory
if (file_exists($newfile)) {
$dupname = true;
$i = 2;
while ($dupname) {
$newpath = pathinfo($newfile);
$newfile = $uploaddir . $newpath['filename'] . '-' . $i . '.' . $newpath['extension'];
if (file_exists($newfile)) {
$i++;
} else {
$dupname = false;
}
}
}
// make a copy of file to new directory
copy($formCopy->uploaded_files[$fieldName], $newfile);
// save the path to the copied file to the cfdb database
$formCopy->posted_data[$fieldName] = $newfile;
$path = pathinfo($newfile);
$filelink = '<a href=' . $urlDir . $path['basename'] . '>' . $path['basename'] . '</a>';
$formCopy->posted_data[$fieldName . '-url'] = $filelink;
// delete the original file from $formCopy
unset($formCopy->uploaded_files[$fieldName]);
return $formCopy;
}
return $formData; }
add_filter('cfdb_form_data', 'cfdbFilterSaveFile');
Now with this code the file is saved into the folder on the server as expected but i am not able to output the clickable link to the saved file in the admin panel tables. In place of clickable links the full url is there. As in the screenshot.
ScreenShot
The output is coming as full URL (as marked 1 in screenshot), while i want the url to output as a link to the file (something like 2 in screenshot). I tried to use echo() and sprintf but got php syntex error.
Thanks for the suggestions. I have found alternate way to output links. What I have to do is output the form submission data on a webpage and convert links clickable by javascript as suggested by #Ovidash ... That is a acceptable workaround for my issue. Thanks for all the suggestions.
I'm using the following code to display the name of a CSV file before the contents of the CSV file are displayed on a PHP page. It works well and displays the name of the file as it should:
CODE:
#$result .= '<h3>'.$prog.'</h3>'.PHP_EOL; // OLD STYLE
$result .= '<h3>'.$prog. ' '.$_POST['filename'].'</h3>'.PHP_EOL; // NEW STYLE
$result .= '</div>'.PHP_EOL;
$result .= $contents.PHP_EOL;
Problem is, I don't want the file name to display the extension (in my code example, it is .csv)
Can anyone assist in the right code needed to remove the extension (.CSV)...?
// Use this code I hope it's useful ..
=> The basename() function returns the filename
<?php
$path = "filename.CSV"; // set your file name
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".CSV");
?>
OutPut :-
filename.CSV
filename
OR
// you also use pathinfo() function .
$file_name = pathinfo('filename');
echo $file_name['dirname'], "\n";
echo $file_name['basename'], "\n";
echo $file_name['extension'], "\n";
echo $file_name['filename'], "\n"
==> Check this Demo Link :-
https://eval.in/930790
I'm trying to fetch gamerscore data from gamercard.xbox.com with my little script:
test.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$regex = '/<div id=\"Gamerscore\">(.+?)<\/div>/';
$gamertag = 'Stallion83';
try {
$URL = file_get_contents('http://gamercard.xbox.com/en-US/' . $gamertag . '.card');
if ($URL == false) {
echo 'Error!';
}
} catch (Exception $e) {
echo $e;
}
preg_match($regex, $URL, $gs);
// Extract integer value from string
$gamerscore = filter_var($gs[1], FILTER_SANITIZE_NUMBER_INT);
// Force gs_int to be integer so it can be used with number_format later
$gs_int = (int)$gamerscore;
$textFile = 'data/gamerscore_' . $gamertag . '.txt';
// Save gamerscore value into everyone's own txt file
file_put_contents($textFile, $gs_int);
?>
Now this works and it creates a .txt file in the data folder which has only the gamerscore number inside. But my problem is if I run the script again after the gamerscore value has increased the script doesn't give me any errors and it seems to execute just fine but the gamerscore value it saves into the .txt file is the old value.
I can go to the URL http://gamercard.xbox.com/en-US/Stallion83.card and see the number is different than my script shows.
I thought it might be a caching issue but I think file_get_contents doesn't use caching.
Is there anything else I could set for file_get_contents to force it to get the most recent content of the URL specified? I tried using timeout but it didn't make any difference.
This is most likelly caused by cache. In this case, the server seems to be returning a cached version of the page.
Often, adding a random value to the URL can be a workaround, such as ?foo.
So, in your case, something like:
[...] . $gamertag . 'card?' . mt_rand());
I would like to show all files i share on my owncloud instance on my "normal" homepage.
The URL of my owncloudserver is: https://cloud.berndklaus.at/public.php?service=files&t=187e4767cb0421c7505cc3ceee450289
From there i would like to show the Filename, the Size and the Last modified Date on my Hompage. I'm actually able to display the Filename and the Last modified name but not the Filesize.
I tried several thinks, but nothing worked, could u help me out?
Sorry for my (bad) english!! :)
Code to display:
$html = file_get_html('https://cloud.berndklaus.at/public.php?service=files&t=187e4767cb0421c7505cc3ceee450289');
//find the table
$td = $html->find('td');
//find all links inside the table
foreach($td as $tds)
{
// Output the Links
//echo $tds;
echo $tds->find('a',0) . "-";
echo $tds->find('span[class=modified]', 0)->plaintext;
}
?>
Here's clean way to retrieve the wanted informations... The idea is to retrieve all rows then extract the useful data inside a loop :
$url = "https://cloud.berndklaus.at/public.php?service=files&t=187e4767cb0421c7505cc3ceee450289";
//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load_file($url);
// Find all rows (files)
$files = $html->find('#fileList tr[data-id]');
// loop through all found files, extract and print the content
foreach($files as $file) {
$fileName = $file->find('span.nametext', 0)->plaintext;
$fileSize = $file->find('td.filesize', 0)->plaintext;
$modDate = $file->find('span.modified', 0)->title;
echo $fileName . " # " . $fileSize . " # " . $modDate . "<br>";
}
// Clear DOM object
$html->clear();
unset($html);
OUTPUT
Christi und Bernd - XMAS.JPG # 363.1 kB # December 29, 2013 10:59
Working DEMO
I wrote a very simple web form that allows my user to view text files from within their Internet browser.
Occasionally, the search criteria entered returns more than one file. So I want to implement a feature whereby the text files returned by the search are compressed into a ZIP.
I got a prototype working but it only compresses the first file. The second or third files are ignored.
Here's my code
<HTML><body><form name="myform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset><label for="DBRIDs">RIDs</label><input type="text" id="DBRIDs" name="DBRIDs" >
</fieldset></form></body></HTML>
<?php
function check_search() {
if (isset($_POST['submit'])) {if (!empty($_POST['DBRIDs'])) { $results = getFiles(); }
} else $errors = "Please enter something before you hit SUBMIT.";
return Array($results, $errors);
}
function getFiles() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select filename from search_table where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename;
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
} return $result;
}
The hyperlinks pointing to the file(s) are generated just fine. The ZIP file however only contains the first file listed in the results.
How can I get the ZIP file to capture ALL the files returned??
Thanks for your input.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
There are a number of issues here (security, for one, as it appears that you're not sanitizing your DB inputs), but I'm guess the issue is around the $ZIPresult variable. It doesn't appear (unless I'm missing something) that you have any spaces between your file names, so the shell_exec call is trying to zip "file1.extfile2.extfile3.ext". See what happens if you modify this line:
$ZIPresult .= basename($mydir) . '/' . $filename.' ';