1

This is the first time that I try to generate a Word document with Laravel.

I have in database columns that I should to generate in a Word document.

For example I have the following database:

enter image description here

I should generate a document file which contains hello John for example

So all the elements that is inside '<<>>' are a dynamic variables .

How can I get from database the value of the column preamble and set the variable name in the same time?

I found that exists a package names phpwordn but I found that I should have a template that is a word file with dynamic variables n but in my case I have no template I have all the components of my Word file in the database.

Is it possible to do that?

If you have any idea or an example to do that help me.

1 Answer 1

1

You can use preg_replace_callback() to convert all special tags to their corresponding values. In your case a tag has a form of <<foo>>, so here it goes:

$values = [
    'me' => 'user14053977',
    'saviour' => 'RoboRobok',
];

$template = 'My name is <<me>> and <<saviour>> saved me!';

$result = preg_replace_callback(
    '#<<(\w+)>>#',
    function (array $matches) use ($values): string {
        [$tag, $tagName] = $matches;
        return $values[$tagName] ?? $tag;
    },
    $template
);

// $result is now "My name is user14053977 and RoboRobok saved me!"

It's a pure PHP code. Now it's just the matter of using the values in Laravel and injecting $result to your Word document.

Sign up to request clarification or add additional context in comments.

4 Comments

thank your for your answer , but I have not a template , the template I must get it also from database , for exapme the 'my names is' is also a value of a column into database which I should get from database and put in a word document
Yeah I know, but what's the problem? You're asking how to retrieve these values from the database too?
yes exactly , how to generate the document word with values from database column and inside this values extracted from database I have also a dynamic variables
I know very well what that means stackoverflow , Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.