Replies: 3   Views: 292
Delete entire table if no data
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by rstoeber  · 07-12-2021 - 17:21

Sometimes our user has no data for the table in a template. In this case, the table is rendered anyway and will display one row of the variables. That is not an optimal result.

I see functions called removeTemplateVariable and deleteTemplateBlock, but I can't figure out if they will do what we need. And my tests so far have not been successful.

Is there a way to delete the table completely if no data available? Is there an example of this?

Posted by admin  · 07-12-2021 - 17:36


The best approach is using removeWordContent included in DOCXPath. This method allows removing contents, for example a whole table. You can generate a code to remove a table according to its contents, position, attributes and other queries. In the package you can find many samples using DOCXPath methods. If you know in your code if a table will filled with data or not, you can use replaceTableVariable or any other method to add the new data and use removeWordContent to remove those tables that won't be needed.

removeTemplateVariable removes a single placeholder and deleteTemplateBlock is designed to work with block of contents instead of a single content ( Although deleteTemplateBlock can work with single contents, removeWordContent is a better approach.


Posted by rstoeber  · 07-12-2021 - 18:04

Thank you! That worked perfectly on my first try!!!

If there is no data for the table, I simply created one row of fake data containing recognizable text, then placed that into the table with replaceTableVariable(). After that I deleted the table following the example like this:

  $referenceNode = array(
    'type' => 'table',
    'contains' => 'DeleteDelete',


The user is making the template so I don't know anything about it unless I insert my own content. Does this sound like a good approach, or is there an easier way?

I think your reply stopped one or two words short. You said "deleteTemplateBlock is designed to work with ." 

What is that designed to work with?

Posted by admin  · 07-12-2021 - 18:11


It's a very good approach. An alternative solution, that could be faster because you don't need to call replaceTableVariable to add a DeleteDelete string, would be removing the tables that contain placeholders (or empty data) after all replacements have been done. If a table contains placeholders then no data has been added and it could be removed.

We have updated the reply with the deleteTemplateBlock information that was removed by mistake :)