开发者

How do I convert a Word document to XML using PHP?

开发者 https://www.devze.com 2023-01-12 04:58 出处:网络
I want to convert Word documents (.doc and .docx) to XML. How i can do this using PHP? Once I have done that, I have to add some data in that XML file.开发者_JS百科

I want to convert Word documents (.doc and .docx) to XML. How i can do this using PHP?

Once I have done that, I have to add some data in that XML file.开发者_JS百科

Could anyone please help me?


A Word document (docx) is a xml file. Simply unzip it.


<?php
$zip = new ZipArchive; // creating object of ZipArchive class.
$sUploadedFile = 'publisher.docx';
$zip->open("word_document/$sUploadedFile");
$aFileName = explode('.',$sUploadedFile);
$sDirectoryName =  current($aFileName);

if (!is_dir("word_document/$sDirectoryName")){
    mkdir("word_document/$sDirectoryName");
    $zip->extractTo("word_document/$sDirectoryName"); 
    copy("word_document/$sDirectoryName/word/document.xml", "xml_document/$sDirectoryName.xml");

    $xml = simplexml_load_file("xml_document/$sDirectoryName.xml");
    $xml->registerXPathNamespace('w',"http://schemas.openxmlformats.org/wordprocessingml/2006/main");
    $text = $xml->xpath('//w:t');

    echo '<pre>'; print_r($text); echo '</pre>';

    rrmdir("word_document/$sDirectoryName");
}

function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           rrmdir($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }

?>


The best way to make an xml file via PHP is the XML DOM class.

http://www.w3schools.com/php/php_xml_dom.asp

0

精彩评论

暂无评论...
验证码 换一张
取 消