Fetch JSON, Save to MongoDB, and Export to Word Document with PHP Full Guide
Fetch JSON Data, Save to MongoDB, and Display in jQuery Table with Word Document Export in PHP
This comprehensive guide demonstrates how to:
Fetch data from a JSON URL in PHP.
Store the data into a MongoDB database.
Display the data in a dynamic jQuery DataTable.
Export the table data to a Word document (.docx) using PHP.
Step 1: Prerequisites
PHP Version: PHP 7.4 or higher.
MongoDB: Ensure MongoDB is installed and running.
Composer: Required for installing libraries.
Node.js/npm: For managing frontend libraries like jQuery DataTables.
Step 2: Install Required Libraries
MongoDB PHP Driver: Install using Composer:
composer require mongodb/mongodb
PHPWord Library: For generating Word documents:
composer require phpoffice/phpword
Step 3: Fetch Data from JSON URL and Save to MongoDB
Create a file named fetch_and_save.php:
<?php
require 'vendor/autoload.php'; // Load Composer libraries
use MongoDB\Client;
// MongoDB configuration
$mongoClient = new Client("mongodb://localhost:27017");
$database = $mongoClient->tutorial_db;
$collection = $database->students;
// Fetch JSON data from URL
$jsonUrl = 'https://api.example.com/students'; // Replace with a valid JSON URL
$jsonData = file_get_contents($jsonUrl);
$data = json_decode($jsonData, true);
// Save data to MongoDB
if ($data && is_array($data)) {
$collection->deleteMany([]); // Clear existing data
$collection->insertMany($data); // Insert new data
echo "Data successfully saved to MongoDB.";
} else {
echo "Failed to fetch or decode JSON data.";
}
?>
Step 4: Display Data in jQuery DataTable
Create an endpoint get_data.php to fetch data from MongoDB for display:
<?php
require 'vendor/autoload.php'; // Load Composer libraries
use MongoDB\Client;
// MongoDB configuration
$mongoClient = new Client("mongodb://localhost:27017");
$database = $mongoClient->tutorial_db;
$collection = $database->students;
// Fetch data from MongoDB
$data = $collection->find();
$output = [];
foreach ($data as $item) {
$output[] = $item;
}
// Return data as JSON
header('Content-Type: application/json');
echo json_encode($output);
?>
Create an HTML page index.html with a jQuery DataTable:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Data Table</title>
<!-- Include jQuery and DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h1>Student Data Table</h1>
<table id="studentTable" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id="exportWord">Export to Word</button>
<script>
$(document).ready(function() {
$('#studentTable').DataTable({
ajax: 'get_data.php',
columns: [
{ data: '_id.$oid' },
{ data: 'name' },
{ data: 'email' },
{ data: 'course' }
]
});
$('#exportWord').on('click', function() {
window.location.href = 'export_docx.php';
});
});
</script>
</body>
</html>
Step 5: Export to Word Document
Create export_docx.php to generate a Word document:
<?php
require 'vendor/autoload.php'; // Load Composer libraries
use MongoDB\Client;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
// MongoDB configuration
$mongoClient = new Client("mongodb://localhost:27017");
$database = $mongoClient->tutorial_db;
$collection = $database->students;
// Fetch data from MongoDB
$data = $collection->find();
// Create Word document
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText('Student Data', ['bold' => true, 'size' => 16]);
$table = $section->addTable();
$table->addRow();
$table->addCell(2000)->addText('ID');
$table->addCell(2000)->addText('Name');
$table->addCell(2000)->addText('Email');
$table->addCell(2000)->addText('Course');
foreach ($data as $item) {
$table->addRow();
$table->addCell(2000)->addText($item['_id']);
$table->addCell(2000)->addText($item['name']);
$table->addCell(2000)->addText($item['email']);
$table->addCell(2000)->addText($item['course']);
}
// Save and send to browse
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename="students.docx"');
header('Cache-Control: max-age=0');
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('php://output');
exit;
?>
Comments
Post a Comment