PHP通用文件处理与格式转换引擎文件格式转换是常见需求。PHP可以处理多种文件格式的转换。今天说说PHP中通用文件处理引擎的实现。文件格式检测和读取是处理的第一步。phpinterface FileReader{public function read(string $path): array;public function supports(string $extension): bool;}interface FileWriter{public function write(string $path, array $data): void;public function supports(string $extension): bool;}class CsvReader implements FileReader{public function read(string $path): array{$handle fopen($path, r);$headers fgetcsv($handle);$data [];while (($row fgetcsv($handle)) ! false) {$row array_map(function ($value) {$value trim($value);if (is_numeric($value)) return str_contains($value, .) ? (float)$value : (int)$value;return $value;}, $row);$data[] $headers ? array_combine($headers, $row) : $row;}fclose($handle);return $data;}public function supports(string $extension): bool{return in_array(strtolower($extension), [csv, tsv]);}}class JsonReader implements FileReader{public function read(string $path): array{$content file_get_contents($path);$data json_decode($content, true);if ($data null) {throw new \RuntimeException(JSON解析失败: . json_last_error_msg());}return $data;}public function supports(string $extension): bool{return strtolower($extension) json;}}class XmlReader implements FileReader{public function read(string $path): array{$xml simplexml_load_file($path);$json json_encode($xml);return json_decode($json, true);}public function supports(string $extension): bool{return in_array(strtolower($extension), [xml, xmls]);}}class CsvWriter implements FileWriter{public function write(string $path, array $data): void{$handle fopen($path, w);if (!empty($data)) {fputcsv($handle, array_keys($data[0]));foreach ($data as $row) {fputcsv($handle, $row);}}fclose($handle);}public function supports(string $extension): bool{return strtolower($extension) csv;}}class JsonWriter implements FileWriter{public function write(string $path, array $data): void{file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));}public function supports(string $extension): bool{return strtolower($extension) json;}}class FileConversionEngine{private array $readers [];private array $writers [];public function __construct(){$this-registerDefaultReaders();$this-registerDefaultWriters();}public function registerReader(FileReader $reader): void{$this-readers[] $reader;}public function registerWriter(FileWriter $writer): void{$this-writers[] $writer;}public function convert(string $sourcePath, string $destPath): void{$sourceExt pathinfo($sourcePath, PATHINFO_EXTENSION);$destExt pathinfo($destPath, PATHINFO_EXTENSION);$reader $this-findReader($sourceExt);if ($reader null) {throw new \RuntimeException(不支持的源格式: {$sourceExt});}$writer $this-findWriter($destExt);if ($writer null) {throw new \RuntimeException(不支持的目标格式: {$destExt});}echo 正在读取: {$sourcePath}\n;$data $reader-read($sourcePath);echo 正在写入: {$destPath}\n;$writer-write($destPath, $data);echo 转换完成\n;}public function getSupportedFormats(): array{$readFormats [];foreach ($this-readers as $reader) {$readFormats[] $reader;}return [readable $readFormats,writable $this-writers,];}private function registerDefaultReaders(): void{$this-readers[] new CsvReader();$this-readers[] new JsonReader();$this-readers[] new XmlReader();}private function registerDefaultWriters(): void{$this-writers[] new CsvWriter();$this-writers[] new JsonWriter();}private function findReader(string $extension): ?FileReader{foreach ($this-readers as $reader) {if ($reader-supports($extension)) return $reader;}return null;}private function findWriter(string $extension): ?FileWriter{foreach ($this-writers as $writer) {if ($writer-supports($extension)) return $writer;}return null;}}$engine new FileConversionEngine();$tempDir /tmp/conversion_test;if (!is_dir($tempDir)) mkdir($tempDir, 0755, true);$csvFile {$tempDir}/test.csv;$fp fopen($csvFile, w);fputcsv($fp, [name, age, email]);fputcsv($fp, [张三, 28, zhangsantest.com]);fputcsv($fp, [李四, 35, lisitest.com]);fclose($fp);try {$engine-convert($csvFile, {$tempDir}/output.json);$engine-convert($csvFile, {$tempDir}/output.xml);$jsonData json_decode(file_get_contents({$tempDir}/output.json), true);print_r($jsonData);} catch (\Exception $e) {echo 错误: {$e-getMessage()}\n;}?文件转换引擎通过策略模式实现了格式的可扩展性。添加新的文件格式只需要注册对应的Reader和Writer类。这种设计让引擎可以处理多种文件格式的相互转换包括CSV、JSON、XML等常见格式。
PHP通用文件处理与格式转换引擎
发布时间:2026/6/4 8:20:05
PHP通用文件处理与格式转换引擎文件格式转换是常见需求。PHP可以处理多种文件格式的转换。今天说说PHP中通用文件处理引擎的实现。文件格式检测和读取是处理的第一步。phpinterface FileReader{public function read(string $path): array;public function supports(string $extension): bool;}interface FileWriter{public function write(string $path, array $data): void;public function supports(string $extension): bool;}class CsvReader implements FileReader{public function read(string $path): array{$handle fopen($path, r);$headers fgetcsv($handle);$data [];while (($row fgetcsv($handle)) ! false) {$row array_map(function ($value) {$value trim($value);if (is_numeric($value)) return str_contains($value, .) ? (float)$value : (int)$value;return $value;}, $row);$data[] $headers ? array_combine($headers, $row) : $row;}fclose($handle);return $data;}public function supports(string $extension): bool{return in_array(strtolower($extension), [csv, tsv]);}}class JsonReader implements FileReader{public function read(string $path): array{$content file_get_contents($path);$data json_decode($content, true);if ($data null) {throw new \RuntimeException(JSON解析失败: . json_last_error_msg());}return $data;}public function supports(string $extension): bool{return strtolower($extension) json;}}class XmlReader implements FileReader{public function read(string $path): array{$xml simplexml_load_file($path);$json json_encode($xml);return json_decode($json, true);}public function supports(string $extension): bool{return in_array(strtolower($extension), [xml, xmls]);}}class CsvWriter implements FileWriter{public function write(string $path, array $data): void{$handle fopen($path, w);if (!empty($data)) {fputcsv($handle, array_keys($data[0]));foreach ($data as $row) {fputcsv($handle, $row);}}fclose($handle);}public function supports(string $extension): bool{return strtolower($extension) csv;}}class JsonWriter implements FileWriter{public function write(string $path, array $data): void{file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));}public function supports(string $extension): bool{return strtolower($extension) json;}}class FileConversionEngine{private array $readers [];private array $writers [];public function __construct(){$this-registerDefaultReaders();$this-registerDefaultWriters();}public function registerReader(FileReader $reader): void{$this-readers[] $reader;}public function registerWriter(FileWriter $writer): void{$this-writers[] $writer;}public function convert(string $sourcePath, string $destPath): void{$sourceExt pathinfo($sourcePath, PATHINFO_EXTENSION);$destExt pathinfo($destPath, PATHINFO_EXTENSION);$reader $this-findReader($sourceExt);if ($reader null) {throw new \RuntimeException(不支持的源格式: {$sourceExt});}$writer $this-findWriter($destExt);if ($writer null) {throw new \RuntimeException(不支持的目标格式: {$destExt});}echo 正在读取: {$sourcePath}\n;$data $reader-read($sourcePath);echo 正在写入: {$destPath}\n;$writer-write($destPath, $data);echo 转换完成\n;}public function getSupportedFormats(): array{$readFormats [];foreach ($this-readers as $reader) {$readFormats[] $reader;}return [readable $readFormats,writable $this-writers,];}private function registerDefaultReaders(): void{$this-readers[] new CsvReader();$this-readers[] new JsonReader();$this-readers[] new XmlReader();}private function registerDefaultWriters(): void{$this-writers[] new CsvWriter();$this-writers[] new JsonWriter();}private function findReader(string $extension): ?FileReader{foreach ($this-readers as $reader) {if ($reader-supports($extension)) return $reader;}return null;}private function findWriter(string $extension): ?FileWriter{foreach ($this-writers as $writer) {if ($writer-supports($extension)) return $writer;}return null;}}$engine new FileConversionEngine();$tempDir /tmp/conversion_test;if (!is_dir($tempDir)) mkdir($tempDir, 0755, true);$csvFile {$tempDir}/test.csv;$fp fopen($csvFile, w);fputcsv($fp, [name, age, email]);fputcsv($fp, [张三, 28, zhangsantest.com]);fputcsv($fp, [李四, 35, lisitest.com]);fclose($fp);try {$engine-convert($csvFile, {$tempDir}/output.json);$engine-convert($csvFile, {$tempDir}/output.xml);$jsonData json_decode(file_get_contents({$tempDir}/output.json), true);print_r($jsonData);} catch (\Exception $e) {echo 错误: {$e-getMessage()}\n;}?文件转换引擎通过策略模式实现了格式的可扩展性。添加新的文件格式只需要注册对应的Reader和Writer类。这种设计让引擎可以处理多种文件格式的相互转换包括CSV、JSON、XML等常见格式。