How to make the setValue function work in PHPWord? - php

I have retrieved the text of a document with PHPWord. Now I would like to modify the data with the setValue function. When I try to do it, it gives me this error:
[05-Jan-2023 17:44:37 UTC] PHP Fatal error: Uncaught BadMethodCallException: Method setvalue is not defined. in /home/bloggors/translatedocs.bloggors.com/vendor/phpoffice/phpword/src/PhpWord/PhpWord.php:148
Stack trace:
#0 /home/bloggors/translatedocs.bloggors.com/controller/test.php(11): PhpOffice\PhpWord\PhpWord->__call('setvalue', Array)
Here is my code:
<?php
use PhpOffice\PhpWord\Element\AbstractContainer;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\IOFactory as WordIOFactory;
require_once 'vendor/autoload.php';
$source = 'test/sample-doc-file-for-testing-1.doc';
$objReader = WordIOFactory::createReader('MsDoc');
$phpWord = $objReader->load($source); // instance of \PhpOffice\PhpWord\PhpWord
$phpWord->setValue('Lorem', 'John');
?>
What should I do to solve this problem please?

setValue is a method for TemplateProcessor. You need to use an exisiting .docx file that has variables with the specified search pattern in them.
Let's say you have template.docx:
Lorem ipsum dolor sit amet, ${varName} adipiscing elit.
What setValue does is replace the ${varName} with the value you specify. For example:
$tProcessor = new TemplateProcessor('path/to/template.docx');
$tProcessor->setValue('varName', 'Replacement Text');
So template.docx becomes:
Lorem ipsum dolor sit amet, Replacement Text adipiscing elit.
You can replace the variables with text, charts, etc by using TemplateProcessor. When you're done replacing the variables you can save the edited file to a new file:
$tProcessor->saveAs('path/to/newFile.docx');
By using saveAs, the original template file won't be modified.
By default the search pattern is ${varName}, but you can specify a custom search pattern if you want. Please refer to the documentation: https://phpword.readthedocs.io/en/latest/templates-processing.html
Don't forget to include the TemplateProcessor if you're editor doesn't automatically add it:
use PhpOffice\PhpWord\TemplateProcessor;

Related

Extracting matching words to JSON file

Is it possible to extract those that match those in the JSON file as separate JSON data?
<?php
$searchArray = array('settings all','print', 'sum', 'industry'); // total 50K words
function sanitize($string,$searchArray) {
$repl = array_map("dashReplace", $searchArray);
$pattern = array_map("insertWordBoundaries", $searchArray);
$string = preg_replace($pattern,$repl,$string);
return $string;
}
function dashReplace($str) {
return "<span class='txtOlg'>" . $str . "</span>";
}
function insertWordBoundaries($str){
return "/\b". preg_quote($str,"/") ."\b/";
}
$text = 'Lorem Ipsum is simply dummy text of the printing and typesettings all industry.';
echo sanitize($text,$searchArray);
Demo
My goal is to pack only the matching words in a separate JSON.
How can I do this, can you guide me?
Ok! after some researches I came up with this, to make a search faster using php and mysql.
1. CREATE INDEX Example
The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the "Persons" table.
CREATE INDEX idx_lastname
ON Persons (LastName);
See here :Slow PHP searching in database
There are several methods creating indexes (combination of columns) etc. you probably know them.
2.FULLTEXT
I use fulltext in all my projects its working fine for me never had a problem for performance.
Mysql site:https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
See here : http://www.bakale.com/mysql/myfultext.htm
Other solutions
check mysql setup and use faster methods and create your columns on that.
Example : char is faster than varchar but char is less word limited.
You need to look into mysql faster methods.
Given answer is the best solution for the way you wanted to do, so I wont give a duplicate answer.
But I realy dont think that solution will make faster your server performance.
Even will make it more slower, you need to look into mysql setup and how to make it faster, how to send minimum queries etc...
You could use array_intersect($array1, $array2); which gives you an array where both arrays have that value. https://www.php.net/manual/en/function.array-intersect.php
<?php
$searchArray = array('settings all','print', 'sum', 'industry');
$text = 'Lorem Ipsum is simply dummy text of the printing and typesettings all industry.';
$text = str_replace('.', '', $text); // and any other characters you dont want
$checkArray = explode(' ', $text);
var_dump(array_intersect($searchArray, $checkArray));
https://3v4l.org/17cWj
The only problem with this approach is that one of your words is actually TWO words, so matching settings all wouldn't work.

Can't pass a variable from php to exec

I have some PHP code which gets the contents from "php://input".
if (!isset($HTTP_RAW_POST_DATA)) {
$HTTP_RAW_POST_DATA = file_get_contents("php://input");
Now, I'm trying to remove the XML tags from $HTTP_RAW_POST_DATA using sed, like this:
exec("/usr/bin/sed -e 's/\<3\>//g' -e 's/\<\/3\>//g' $HTTP_RAW_POST_DATA");
Then, I try echoing $HTTP_RAW_POST_DATA like this:
echo("$HTTP_RAW_POST_DATA");
But it still returns it with <3> and </3>. Seems like sed can't read the variable.
What can I do to fix this? I get no error messages.
Just use strip_tags() - http://php.net/manual/en/function.strip-tags.php - does exactly what you want sed to do without the horrible security implications.

Limit the number of words of a post shown on the home page of a wordpress blog

currently my wordpress theme shows all the words in a post on the homepage, even of very long posts. I would like to limit that to a reasonable number lets say 1500 words max to be shown on the home page, then there should be a "read more" link underneath.
Im using the toolbox theme heres the 1. content.php and 2 index.php.
1. http://i.stack.imgur.com/rUWZv.png
2. http://i.stack.imgur.com/YrZGS.png
You could use the 'insert more tag' in the wordpress WYSIWYG.
Otherwise you could use something like this to limit the word count:
//define the number of words
$length = 1500;
$text = "Lorem Ipsum dolar sit amet etc etc"; //this would contain the article you are pulling from the database and syntax will depend largely on your theme.
$shortened = implode(' ',array_slice(str_word_count($text,1),0,$length));
echo $shortened . ' ...';
(Take this as pseudocode for now as I dont have time to test it.)
Then link to the article:
read more

extra spaces inserted with CKeditor's enterMode - causes problems in XML docs

I am using CKEditor in my website's CMS, which spits out an XML file of CDATA enclosed content to be read by flash. The problem is that CKEditor, when its enterMode is set to <p> tags, creates a line break and a tab in the source which, when read by flash, enters space, even though I have ignoreWhiteSpace set to true. Any way to prevent ckeditor from using this behavior?
EDIT:
I still want to keep any <p> tags entered from within the editor - I just don't want all the extra space / tabs that get added in the actual source. If I use the above method, my actual code will be modified. What I'm getting if I view the source is this:
<p>
Donec at erat nec tortor sodales tempus.</p>
(an enter, and either a tab or a bunch of space after first <p> tag, instead of:
<p>Donec at erat nec tortor sodales tempus.</p>
(no spaces or breaks after <p> tag in source and I believe this is affecting the presentation of the XML. Does this help clarify at all?
You should test the "output for Flash" sample, here's a little snippet that changes just the part that you are asking, but the rest of the adjustments should be useful for you:
// Make output formatting match Flash expectations
var dtd = CKEDITOR.dtd;
for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) )
{
dataProcessor.writer.setRules( e,
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
});
}
dataProcessor.writer.setRules( 'br',
{
indent : false,
breakBeforeOpen : false,
breakAfterOpen : false,
breakBeforeClose : false,
breakAfterClose : false
});
I actually solved this on the Flash end, by using
TextField.condenseWhite = true;
and
XML.ignoreWhite = true;
Which doesn't change how CKEditor spits stuff out, but it does solve the problem of how flash displays it.

Symfony doctrine data-load segmentation fault

I'm working through the Symfony Jobeet tutorial and am getting a segmentation fault when trying to load data from my fixtures files.
PHP 5.2.6-1+lenny8 with Suhosin-Patch 0.9.6.2 (cli), S
symfony version 1.4.5
I'm using the Doctrine plugin.
My fixtures below:
/data/fixtures/categories.yml
JobeetCategory:
design:
name: Design
programming:
name: Programming
manager:
name: Manager
administrator:
name: Administrator
/data/fixtures/jobs.yml
JobeetJob:
job_sensio_labs:
JobeetCategory: programming
type: full-time
company: Sensio Labs
logo: sensio-labs.gif
url: http://www.sensiolabs.com/
position: Web Developer
location: Paris, France
description: |
You've already developed websites with symfony and you want to work
with Open-Source technologies. You have a minimum of 3 years
experience in web development with PHP or Java and you wish to
participate to development of Web 2.0 sites using the best
frameworks available.
how_to_apply: |
Send your resume to fabien.potencier [at] sensio.com
is_public: true
is_activated: true
token: job_sensio_labs
email: job#example.com
expires_at: '2010-10-10'
job_extreme_sensio:
JobeetCategory: design
type: part-time
company: Extreme Sensio
logo: extreme-sensio.gif
url: http://www.extreme-sensio.com/
position: Web Designer
location: Paris, France
description: |
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in.
Voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.
how_to_apply: |
Send your resume to fabien.potencier [at] sensio.com
is_public: true
is_activated: true
token: job_extreme_sensio
email: job#example.com
expires_at: '2010-10-10'
expired_job:
JobeetCategory: programming
company: Sensio Labs
position: Web Developer
location: Paris, France
description: Lorem ipsum dolor sit amet, consectetur adipisicing elit.
how_to_apply: Send your resume to lorem.ipsum [at] dolor.sit
is_public: true
is_activated: true
created_at: '2005-12-01 00:00:00'
token: job_expired
email: job#example.com
<?php for ($i = 100; $i <= 130; $i++): ?>
job_<?php echo $i ?>:
JobeetCategory: programming
company: Company <?php echo $i."\n" ?>
position: Web Developer
location: Paris, France
description: Lorem ipsum dolor sit amet, consectetur adipisicing elit.
how_to_apply: |
Send your resume to lorem.ipsum [at] company_<?php echo $i ?>.sit
is_public: true
is_activated: true
token: job_<?php echo $i."\n" ?>
email: job#example.com
<?php endfor ?>
I've followed the tutorial exactly as it says, I'm on day 7 (http://www.symfony-project.org/jobeet/1_4/Doctrine/en/07) at the Job Category Module Creation then Update Database.
I'm really not sure what could be causing this.
Any ideas?
Thanks
Segmentation faults are usually either incorrect opcode caches or broken modules. I'd disable opcode caches like apc first, and if the problem still persists, keep disabling php-modules on at a time to determine which one gives you problems.
If even that doesn't work, try to upgrade php (5.2.13 or 5.3.2 are considered stable), and report a bug in to bugs.php.net if the problem persist with a minimum use case.
For arguments sake, I would like to share the way I resolved a similar error.
I had issues in a fixtures logic I was reviewing that would return the same code: Segmentation fault
Basically, the same var was overwritten in a loop after being declared and passed as arguments in methods, yeah I know, what a ride :)
So by defining other vars and properly reassigning them around, the error completely vanished...
Hope that helps someone else reaching this page like i did!
Concerning your case, if the other answer was not resolving it, you may want to try and correct your code in the template part by adding a ; after the endfor closing directive.
When this happens to me when working on symfony project, first I check logs, but not always can found the solution. If not, I run some symfony command from the project I am working on that I have programmed to see if some described error is shown in console.
I also check last changes I've done and try to rollback parts of code.
Last time It happened to my was because of an incorrect parameter in a yml file, just a "parent" class.
Hope it helps to think about how to think about the problem.

Categories