Transform a JSON dataset into a visually appealing PDF document using mPDF

My current project involves converting a JSON file to a PDF using mPDF. However, I'm encountering an issue where the JSON table is not being displayed in the HTML after running the PHP code. Instead, only one empty PDF page is generated.

UPDATE: I have made some modifications to the code and now it's almost working correctly. The code successfully creates the table but fails to display all of the JSON Data.

Updated PHP Code

ob_start();
$json = file_get_contents($url);
$json_decoded= json_decode($json);

foreach ($json_decoded as $result) {
$html = '
  <!DOCTYPE html>
  <html>
  <head>
      <title>Convert JSON Data to HTML Table</title>
      <link href="style.css" rel="stylesheet">
      <meta charset="UTF-8">
  </head>
  <body>
      <table>
          <tr>
              <th>driverno</th>
              <th>name</th>
              <th>objectno</th>
              <th>tagId</th>
              <th>lastScanDate</th>
          </tr>
          <tr>
            <td>'.$result->driverno.'</td>
            <td>'.$result->name.'</td>
            <td>'.$result->objectno.'</td>
            <td>'.$result->tagID.'</td>
            <td>'.$result->lastScanDate.'</td>
          </tr>
          <tr>
            <td>'.$result->driverno.'</td>
            <td>'.$result->name+'</td>
            <td>'.$result->objectno+'</td>
            <td>'.$result->tagID+'</td>
            <td>'.$result->lastScanDate+'</td>
          </tr>
      </table>
  </body>


  </html>

';

}

$mpdf->WriteHTML($html);
$mpdf->Output("demo.pdf", 'F');
$mpdf->Output();
?>

JSON Data

 {
  "driverno":1,
  "name":"Aragorn",
  "objectno":1,
  "tagId":1,
  "lastScanDate":"yesterday"   
 },
 {
  "driverno":2,
  "name":"Legolas",
  "objectno":2,
  "tagId":2,
  "lastScanDate":"today"  
 },
 {
  "driverno":3,
  "name":"Gimmli",
  "objectno":3,
  "tagId":3,
  "lastScanDate":"today"

 },
 {
  "driverno":4,
  "name":"Gandalf",
  "objectno":4,
  "tagId":4,
  "lastScanDate":"today" 
 }

The issue persists with the last data of the JSON file without displaying the tagID.

Answer №1

When working with mPDF, it's important to note that Javascript is not fully supported.

To handle JSON data in PHP, you should use

$table = json_decode($json, true)
to decode the JSON and then iterate over it using foreach ($json as $row) to create HTML table markup manually.

Make sure to construct the HTML code as a string in a variable instead of echoing it directly (refer to this SO answer).

After building the table HTML string, you can pass it to mPDF by using $mpdf->WriteHtml().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing JSON data stored as keys within a JavaScript object

I'm facing an issue with my Node.js lambda function that involves parsing JSON data received from an external application. The JSON data seems to be malformed and arrives as an object key, shown below: console.log(req.body) This results in: { &apo ...

Creating interactive forms with Symfony2 using embedded forms and event listeners

I created a form called "AddressType" with an event listener that functions correctly when used independently. Below is the code: namespace Nc\ClientsBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Componen ...

Guide to adding a Json file in a PHP file with PHP

I have a PHP file with an embedded JSON file, and I want to update the JSON file with new information from a form. The form looks like this: <form action="process.php" method="POST"> First name:<br> <input type="text" name="firstName"> ...

How can one go about changing the active Drupal theme through code?

How can I programmatically switch the current Drupal theme to a different one? ...

Understanding the process of unmarshalling an array within a POST request

I am attempting to send an array of JSON data with a POST request to an API server. However, I keep encountering the following error: cannot unmarshal array into Go value of type models.UserRequest Despite trying to unmarshal the data using a factory and ...

Can you provide guidance on extracting keys and values from a JSON object in Java?

After successfully extracting data from a website, I received the following response: {"vulnerability":{"id":15017916,"status":"open","closed_at":null,"created_at":"2019-07-26T10:06:03Z","due_date":null,"notes":null,"port":[],"priority":null,"identifiers" ...

I am receiving HTML code instead of JSON data when making a NodeJS request to get data

I am attempting to retrieve a JSON object from a GET request. It works fine in Python, but in NodeJs it displays the HTML source code of the page. Below is my NodeJs code: app.get("/well", function(request, response) { const req = require(&ap ...

What is the method for inserting form control values into a QueryString within HTML code?

Struggling with passing HTML form control values into a QueryString for page redirection. While I can easily input static values into a QueryString and retrieve them using PHP's GET method, I am encountering difficulties when it comes to dynamic valu ...

The set command is failing to save data in the JSON file

One of my new commands, known as "muterole", includes various subcommands. Here's how the muterole command is structured: @commands.group(aliases=['mr']) @commands.has_permissions(manage_roles=True) async def muterole(self, ctx): if ctx. ...

Prevent clients from accessing a page that is meant for inclusion only

In the realm of PHP files, header.php is a constant presence and gets included by other files such as index.php, member.php, among others. Is there a way to restrict access for clients to my header.php file? ...

expiration of oauth2 access token

<?php session_start(); require_once realpath(dirname(__FILE__) . '/Google/src/Google/autoload.php'); /************************************************ PLEASE NOTE: Remember to fill in these values! Ensure that the redirect URI points to ...

Exception handling in debugger does not work for JSON null reference, but is successfully caught in other scenarios

In my current project, I am utilizing the System.Text.Json library to work with JsonNode data, some of which may be null. Rather than testing each element for null values, I have opted to wrap the code in a try-catch block. However, I have encountered an u ...

PHP rendering issue

Is there a way to reload a page and keep the user input displayed in the text field exactly as it was originally entered utilizing PHP? For instance, Example 1 should maintain its formatting upon refreshing, unlike Example 2. Example 1 &amp;amp; Exa ...

Ensuring data accuracy with form validation and interactive features with Ajax using Vanilla

I am working on a form that requires validation before submission, and I need to display error notifications without refreshing the page. Below is the code for the form: <button name="save" type="submit" form="product_form" ...

Explain the structure of a nested Pydantic model

Whenever I make a GET request with an ID, the JSON response looks like this: { "data": { "id": "81", "ks": { "k1": 25, "k2": 5 }, " ...

How can JSON.parse() be used to parse multiple JSON arrays simultaneously?

After fetching records from the database, I am constructing an array for each row and using the json_encode() function to encode it. The data is being returned in the following format: [{"slug":"bitcoin","change7d":"-3.87"}][{"slug":"maker","change7d":"-8. ...

The request for a Facebook access token resulted in zero response

After struggling for 5 days with implementing a simple Facebook login, I am feeling extremely frustrated. I have reached a point where I am manually trying to set the accessToken, following the instructions in this post. https://github.com/facebook/php-sd ...

Incorporating Javascript into a <script> tag within PHP - a step-by-step guide

I am trying to integrate the following code into a PHP file: if (contains($current_url, $bad_urls_2)) { echo '<script> $('body :not(script,sup)').contents().filter(function() { return this.nodeType === 3; ...

Determine the absent information by comparing two JSON objects with JavaScript

Two JSON objects, counties and ctyIndem, are at hand. The counties object contains all the counties in a specific US State, while ctyIndem holds information about indemnities paid in that State by county, excluding those with no payments made. My task is t ...

Having difficulty interpreting the json data retrieved from the specified url

<html> <body> <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script> <script> $(document).ready(function () { $.ajax({ type: 'GET& ...