PHP Code - import xml file from web server (/public_html/ctrackxml) into mysql database

前端 未结 5 1693
无人共我
无人共我 2021-01-07 02:26

I have xml files been imported onto an FTP server. This is stored in location \'/public_html/ctrackxml/\' with a random file name and in the following format:



        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-07 03:22

    I recently worked on a project that has some similarities to what you require. As Charles suggested, I used simplexml for the parsing. My task also required connecting via ftp to a server, getting files, unzipping them in a directory etc.

    My approach was to write a script that processes one file, uses simplexml to read the document, do some simple transforms and write the data to mysql.

    I then created a simple bash script wrapper that reads all the files in a directory and for each one, passes it as the parameter to my processing script.

    If you found that your structure is a close enough match to allow for the use of LOAD XML you won't need PHP at all ... just the bash script and repeated calls to the mysql command line client.

    The php script accepts the filename as the command line parameter. Of course this refers to the php CLI. It's actually a class, but its as simple as this to load the file:

    if (file_exists($filename)) {
          $this->xml = simplexml_load_file($filename);
    

    From there you can refer to the elements very easily. This bash script is typical of the what I'm using, where you pass it the directory where all your xml files are, and it just processes them all one by one.

    #!/bin/bash
    if [ $# -ne 1 ]
    then
      echo "No directory specified."
      exit 1
    fi
    DIR="$( cd "$( dirname "$0" )" && pwd )"
    FILES="$1"/*.xml
    for f in $FILES
      do
        /usr/bin/php -f /path/to/yourscript.php $f
    done
    exit 0
    

    If the documents are exactly as you describe then, once you do the load I described above (which assumes you have a simple class to facilitate your xml variable, then you just need to write an insert statement and call it using the mysql_query function. I'd actually recommend you tune the schema so that the column types accurately match the type of data your getting for each column rather than having varchars for numbers. This could be as simple as something like this:

    $msg = $this->xml->message;
    
    $query = "INSERT INTO YOUR TABLE (messageid, mobile...) VALUES ({$msg->message}, '{$msg->mobile}', ...)";
    // assumes you already made db connection previously
    $result = mysql_query($query);
    if ($result) {
    // inserted ok.
    } else {
    // something wrong, check mysql_error() for specifics
    }
    

提交回复
热议问题