通过单个PHP脚本运行数百个文件[关闭]

I need to run 600 XML files through a script I've made that extracts specific pieces of information and saves each one in JSON format. All 600 XML files are inside a folder ready to be run through the PHP file, I'm now looking for a fast way to do it.

Essentially this is the process the PHP file goes through:

PHP reads single XML file via URL -> locally saves important info in variables -> saves important info into JSON file

Is there a way I can somehow run all 600 XML files through my PHP file?

Thanks

Open the directory containing the XML files and then process them, here are some of the most common way todo that.

opendir()

<?php
$dir = "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: $file : filetype: " . filetype($dir . $file) . "
";
        }
        closedir($dh);
    }
}
?>

You can also use glob()

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "
";
}
?>

Inside the foreach loop of whichever you choose you can use file_get_contents() or fread() then you can do your conversion to json.

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Hope it helps

Just go ahead and try! You'll probably run into a timeout error. If you do, try configuring the max timeout settings. http://php.net/manual/en/function.set-time-limit.php

Joel,

Sounds to me like what you need to is to use readdir

http://php.net/manual/en/function.readdir.php

This will allow you to get a list of files in a directory to iterate over.

$dir = opendir('/path/to/files');
while($file = readdir($dir)) {
    if ($file !== '.' && $file !== '..' && !is_dir($file)) {
        $parthParts = pathinfo($file);
        if ($pathParts['extension'] === 'xml') {
            runscripton($file);
        }
    }
}
closedir($dir);

First, write a function that gets an XML file name, and after processing, returns the results in php array or JSON (Based on how you need your code to be).

To write this function, you need to parse XML (http://php.net/manual/en/book.xml.php).

To work with JSON in PHP: http://php.net/manual/en/book.json.php

Then, write your main code. Your main code should enumerate all XML files in the folder, and then call your function for each file, and gather/generate JSON using information returned by the function.

You might need readdir to gather all of XML files in the folder. (http://php.net/manual/en/book.xml.php)

Don't forget to increase time limit as long as there are lots of XML files and the process might take long so a timeout error would occur. (http://php.net/manual/en/function.set-time-limit.php)