Skip to content

Commit f5d0654

Browse files
committed
feat: add export helpers (Db::toJson(), Db::toCsv(), Db::toXml())
Add new helper methods for exporting database results to various formats. Features: - Db::toJson() - Export data to JSON format with customizable encoding - Db::toCsv() - Export data to CSV format with custom delimiters - Db::toXml() - Export data to XML format with customizable elements Implementation: - Created ExportHelpersTrait for helper methods - Created separate exporter classes (JsonExporter, CsvExporter, XmlExporter) - Follows SOLID principles with single responsibility per exporter - All exporters support custom options and parameters Files added: - src/helpers/traits/ExportHelpersTrait.php - src/helpers/exporters/JsonExporter.php - src/helpers/exporters/CsvExporter.php - src/helpers/exporters/XmlExporter.php Documentation: - documentation/07-helper-functions/export-helpers.md - Complete guide - Updated documentation/README.md with export helpers link - Updated main README.md with export helpers section - Added examples/11-export-helpers/ with comprehensive examples Tests: - Added 6 new tests in SharedCoverageTest.php - All tests pass (484 tests, 2224 assertions) - PHPStan level 8 compliant Breaking changes: - None, adds new functionality only
1 parent 273de3f commit f5d0654

File tree

13 files changed

+997
-0
lines changed

13 files changed

+997
-0
lines changed

README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ Comprehensive, runnable examples are available in the [`examples/`](examples/) d
137137
- **[Advanced](examples/03-advanced/)** - Connection pooling, bulk operations, UPSERT
138138
- **[JSON Operations](examples/04-json/)** - Complete guide to JSON features
139139
- **[Helper Functions](examples/05-helpers/)** - String, math, date/time helpers
140+
- **[Export Helpers](examples/11-export-helpers/)** - Export data to JSON, CSV, XML
140141
- **[Real-World](examples/06-real-world/)** - Blog system, user auth, search, multi-tenant
141142
- **[README Examples](examples/07-readme-examples/)** - Examples extracted from this README
142143
- **[Connection Retry](examples/08-connection-retry/)** - Retry mechanism with logging
@@ -1601,6 +1602,27 @@ Db::jsonKeys('meta') // Object keys
16011602
Db::jsonType('tags') // Value type
16021603
```
16031604

1605+
### Export Helpers
1606+
1607+
```php
1608+
use tommyknocker\pdodb\helpers\Db;
1609+
1610+
// Export to JSON
1611+
$data = $db->find()->from('users')->get();
1612+
$json = Db::toJson($data);
1613+
1614+
// Export to CSV
1615+
$csv = Db::toCsv($data);
1616+
1617+
// Export to XML
1618+
$xml = Db::toXml($data);
1619+
1620+
// Custom options
1621+
$json = Db::toJson($data, JSON_UNESCAPED_SLASHES);
1622+
$csv = Db::toCsv($data, ';'); // Semicolon delimiter
1623+
$xml = Db::toXml($data, 'users', 'user'); // Custom elements
1624+
```
1625+
16041626
---
16051627

16061628
## Public API Reference
Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
# Export Helpers
2+
3+
Export database results to various formats: JSON, CSV, and XML.
4+
5+
## JSON Export
6+
7+
### Basic Export
8+
9+
```php
10+
use tommyknocker\pdodb\PdoDb;
11+
use tommyknocker\pdodb\helpers\Db;
12+
13+
$db = new PdoDb('mysql', [...]);
14+
15+
// Get data
16+
$users = $db->find()->from('users')->get();
17+
18+
// Export to JSON
19+
$json = Db::toJson($users);
20+
echo $json;
21+
```
22+
23+
### With Custom Options
24+
25+
```php
26+
// Compact format (no pretty print)
27+
$json = Db::toJson($users, 0);
28+
29+
// Custom flags
30+
$json = Db::toJson($users, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
31+
32+
// Custom depth
33+
$json = Db::toJson($users, JSON_PRETTY_PRINT, 256);
34+
```
35+
36+
### Save to File
37+
38+
```php
39+
// Save JSON to file
40+
$json = Db::toJson($users);
41+
file_put_contents('users.json', $json);
42+
43+
// For download
44+
header('Content-Type: application/json');
45+
header('Content-Disposition: attachment; filename="users.json"');
46+
echo $json;
47+
```
48+
49+
## CSV Export
50+
51+
### Basic Export
52+
53+
```php
54+
$users = $db->find()->from('users')->get();
55+
56+
// Export to CSV
57+
$csv = Db::toCsv($users);
58+
echo $csv;
59+
```
60+
61+
### With Custom Delimiter
62+
63+
```php
64+
// Semicolon delimiter (European format)
65+
$csv = Db::toCsv($users, ';');
66+
67+
// Tab delimiter
68+
$csv = Db::toCsv($users, "\t");
69+
70+
// Pipe delimiter
71+
$csv = Db::toCsv($users, '|');
72+
```
73+
74+
### Custom Enclosure
75+
76+
```php
77+
// Single quote enclosure
78+
$csv = Db::toCsv($users, ',', "'");
79+
80+
// Custom escape character
81+
$csv = Db::toCsv($users, ',', '"', '#');
82+
```
83+
84+
### Save to File
85+
86+
```php
87+
// Save CSV to file
88+
$csv = Db::toCsv($users);
89+
file_put_contents('users.csv', $csv);
90+
91+
// For download
92+
header('Content-Type: text/csv');
93+
header('Content-Disposition: attachment; filename="users.csv"');
94+
echo $csv;
95+
```
96+
97+
## XML Export
98+
99+
### Basic Export
100+
101+
```php
102+
$users = $db->find()->from('users')->get();
103+
104+
// Export to XML
105+
$xml = Db::toXml($users);
106+
echo $xml;
107+
```
108+
109+
### Custom Element Names
110+
111+
```php
112+
// Custom root and item elements
113+
$xml = Db::toXml($users, 'users', 'user');
114+
115+
// With custom encoding
116+
$xml = Db::toXml($users, 'users', 'user', 'ISO-8859-1');
117+
```
118+
119+
### Save to File
120+
121+
```php
122+
// Save XML to file
123+
$xml = Db::toXml($users);
124+
file_put_contents('users.xml', $xml);
125+
126+
// For download
127+
header('Content-Type: application/xml');
128+
header('Content-Disposition: attachment; filename="users.xml"');
129+
echo $xml;
130+
```
131+
132+
## Export Filtered Data
133+
134+
### With Conditions
135+
136+
```php
137+
// Export only active users
138+
$activeUsers = $db->find()
139+
->from('users')
140+
->where('active', 1)
141+
->get();
142+
143+
$json = Db::toJson($activeUsers);
144+
```
145+
146+
### Specific Columns
147+
148+
```php
149+
// Export only specific columns
150+
$userData = $db->find()
151+
->from('users')
152+
->select(['id', 'name', 'email'])
153+
->get();
154+
155+
$csv = Db::toCsv($userData);
156+
```
157+
158+
## Export Complex Data
159+
160+
### Nested Arrays
161+
162+
```php
163+
$complexData = [
164+
[
165+
'id' => 1,
166+
'name' => 'Alice',
167+
'tags' => ['php', 'mysql'],
168+
'metadata' => [
169+
'location' => 'USA',
170+
'status' => 'active'
171+
]
172+
]
173+
];
174+
175+
$json = Db::toJson($complexData);
176+
// Handles nested structures automatically
177+
```
178+
179+
## Empty Data Handling
180+
181+
### Empty Result Sets
182+
183+
```php
184+
$empty = $db->find()
185+
->from('users')
186+
->where('id', 9999)
187+
->get(); // Returns []
188+
189+
// Empty JSON
190+
$json = Db::toJson($empty); // Returns "[]"
191+
192+
// Empty CSV
193+
$csv = Db::toCsv($empty); // Returns ""
194+
195+
// Empty XML
196+
$xml = Db::toXml($empty); // Returns <data/>
197+
```
198+
199+
## Browser Download
200+
201+
### JSON Download
202+
203+
```php
204+
$data = $db->find()->from('users')->get();
205+
$json = Db::toJson($data);
206+
207+
header('Content-Type: application/json');
208+
header('Content-Disposition: attachment; filename="users.json"');
209+
echo $json;
210+
exit;
211+
```
212+
213+
### CSV Download
214+
215+
```php
216+
$data = $db->find()->from('users')->get();
217+
$csv = Db::toCsv($data);
218+
219+
header('Content-Type: text/csv');
220+
header('Content-Disposition: attachment; filename="users.csv"');
221+
echo $csv;
222+
exit;
223+
```
224+
225+
### XML Download
226+
227+
```php
228+
$data = $db->find()->from('users')->get();
229+
$xml = Db::toXml($data);
230+
231+
header('Content-Type: application/xml');
232+
header('Content-Disposition: attachment; filename="users.xml"');
233+
echo $xml;
234+
exit;
235+
```
236+
237+
## Performance Tips
238+
239+
### Memory-Efficient Export
240+
241+
```php
242+
// For large datasets, use batch processing
243+
foreach ($db->find()->from('users')->cursor() as $user) {
244+
// Process individual records without loading all into memory
245+
}
246+
247+
// Then export in chunks
248+
$chunk = [];
249+
foreach ($db->find()->from('users')->batch(1000) as $batch) {
250+
$json = Db::toJson($batch);
251+
// Append to file or process
252+
}
253+
```
254+
255+
## Parameters Reference
256+
257+
### Db::toJson()
258+
259+
```php
260+
Db::toJson(array $data, int $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE, int $depth = 512): string
261+
```
262+
263+
- `$data` - Array of data to export
264+
- `$flags` - JSON encoding flags
265+
- `$depth` - Maximum encoding depth
266+
267+
### Db::toCsv()
268+
269+
```php
270+
Db::toCsv(array $data, string $delimiter = ',', string $enclosure = '"', string $escapeCharacter = '\\'): string
271+
```
272+
273+
- `$data` - Array of data to export
274+
- `$delimiter` - CSV field delimiter
275+
- `$enclosure` - CSV field enclosure
276+
- `$escapeCharacter` - CSV escape character
277+
278+
### Db::toXml()
279+
280+
```php
281+
Db::toXml(array $data, string $rootElement = 'data', string $itemElement = 'item', string $encoding = 'UTF-8'): string
282+
```
283+
284+
- `$data` - Array of data to export
285+
- `$rootElement` - Root XML element name
286+
- `$itemElement` - Individual item element name
287+
- `$encoding` - XML encoding
288+
289+
## Next Steps
290+
291+
- [Core Helpers](core-helpers.md) - Basic helpers
292+
- [Real-World Examples](../10-cookbook/real-world-examples.md) - Practical examples
293+
- [Common Patterns](../10-cookbook/common-patterns.md) - Common patterns
294+

0 commit comments

Comments
 (0)