Php Reads Ods Documents

PHP import ODS documents

Want to read open office spreadsheet(.ods) files with php? Since they are zipped xmlfiles, its really simple. The quick example below shows how to read a simple table structure using zLib(for reading the zipfile) and simplexml to navigate through the xml.

It will return an array with a key:value pairs for each columns. Make sure it works with the file you have, my files where very static and easy to read. Since formatting of the values are done inside the cell, I added the strip_tags() to clear it out. The strip_tags can possibly break any multivalue-entries in there.

    private function parse_openoffice_file($filename) {
        $return = array();
        /* Extremely naive implementation of a open office document parser */
        $content_xml = simplexml_load_file('zip://' . $filename . '#content.xml');
        foreach( $content_xml->xpath('//table:table-row') as $row ){
            $row_values = array();
            foreach( $row->xpath('//table:table-cell/text:p') as $val ){
                $row_values[] = trim(strip_tags((string)$val->asXml()));
            }
 
            /* Headers are halfway of the array */
            $half = (sizeof($row_values)/2);
            $mangled_row = array();
            $headers = array();
            foreach( $row_values as $idx    => $val ){
                if( $idx<$half ) {
                    $headers[] = $val;
                }else{
                    $header_key = $idx-$half;
                    if( isset($headers[$header_key]) )
                        $mangled_row[$headers[$header_key]] = $val;
                }
            }
            $return[] = $mangled_row;
        }
        return $return;
    }


blog comments powered by Disqus