У меня есть конвертер, который преобразует doc и docx в html для этого преобразователя. Файл класса выглядит следующим образом
<?php
class docxhtml {
public $connectname;
public $connectpass;
public function __construct($format_res, $flname) {
require_once('config.php');
// Turn up error reporting
error_reporting (E_ALL|E_STRICT);
// Turn off WSDL caching
ini_set ('soap.wsdl_cache_enabled', 0);
// Define credentials for LD
define ('USERNAME', $this->connectname);
define ('PASSWORD', $this->connectpass);
// SOAP WSDL endpoint
define ('ENDPOINT', 'https://api.livedocx.com/2.1/mailmerge.asmx?wsdl');
// Define timezone
date_default_timezone_set('Europe/Berlin');
// Instantiate SOAP object and log into LiveDocx
$this->soap = new SoapClient(ENDPOINT);
$this->soap->LogIn(
array(
'username' => USERNAME,
'password' => PASSWORD
)
);
// Upload template
$this->data = file_get_contents('Original/'.$format_res);
$this->soap->SetLocalTemplate(
array(
'template' => base64_encode($this->data),
'format' => 'docx'
)
);
$this->result = $this->soap->RetrieveDocument(
array(
'format' => 'html'
)
);
$this->data = $this->result->RetrieveDocumentResult;
file_put_contents('Recode/'.$flname.'.html', base64_decode($this->data));
}
}
?>
Поскольку вы можете видеть, что этот файл класса отправляет преобразованный файл в папку Recode, который затем загружается с помощью диалогового окна сохранения скриптом в интерфейсе PHP.
Теперь мне нужно руководство было.. Я хочу преобразовать этот результат HTML для очистки stripped html, для которого я сделал код, который следует, который хорошо работает
<?php
$path = 'path to previous html output file from local machine';
$html = file_get_contents($path);
$dom = new DOMDocument();
//$dom->strictErrorChecking = false;
$dom->formatOutput = true;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
if (false === ($elements = $xpath->query("//*"))) die('Error');
foreach ($elements as $element) {
for ($i = $element->attributes->length; --$i >= 0;) {
$name = $element->attributes->item($i)->name;
if (('img' === $element->nodeName && 'src' === $name)
|| ('a' === $element->nodeName && 'href' === $name)
) {
continue;
}
$element->removeAttribute($name);
}
}
echo $dom->saveHTML();
?>
Теперь я хочу объединить эти два... то есть в файле первого класса, прежде чем он сохранит данные для перекодировки папки, он должен обработать эти домашние коды, а затем сохранить этот вывод в этой папке перекодировки. Пожалуйста, помогите мне пожалуйста
Попробуйте это решение:
<?php
class docxhtml
{
/** @var string */
private $tag;
/** @var string */
private $attribute;
public $connectname;
public $connectpass;
public function __construct($format_res, $flname)
{
require_once('config.php');
// Turn up error reporting
error_reporting(E_ALL | E_STRICT);
// Turn off WSDL caching
ini_set('soap.wsdl_cache_enabled', 0);
// Define credentials for LD
define ('USERNAME', $this->connectname);
define ('PASSWORD', $this->connectpass);
// SOAP WSDL endpoint
define ('ENDPOINT', 'https://api.livedocx.com/2.1/mailmerge.asmx?wsdl');
// Define timezone
date_default_timezone_set('Europe/Berlin');
// Instantiate SOAP object and log into LiveDocx
$this->soap = new SoapClient(ENDPOINT);
$this->soap->LogIn(
array('username' => USERNAME, 'password' => PASSWORD)
);
// Upload template
$this->data = file_get_contents('Original/' . $format_res);
$this->soap->SetLocalTemplate(
array('template' => base64_encode($this->data), 'format' => 'docx')
);
$this->result = $this->soap->RetrieveDocument(
array('format' => 'html')
);
$this->data = $this->result->RetrieveDocumentResult;
$exceptions = array(
'a' => array('href'),
'img' => array('src')
);
$this->stripAttributes($exceptions);
file_put_contents('Recode/' . $flname . '.html', base64_decode($this->data));
}
public function stripAttributes(array $exceptions)
{
$dom = new DOMDocument();
$dom->strictErrorChecking = false;
$dom->formatOutput = true;
$dom->loadHTML(base64_decode($this->data));
$xpath = new DOMXPath($dom);
if (false === ($elements = $xpath->query("//*"))) die('Xpath error!');
/** @var $element DOMElement */
foreach ($elements as $element) {
for ($i = $element->attributes->length; --$i >= 0;) {
$this->tag = $element->nodeName;
$this->attribute = $element->attributes->item($i)->nodeName;
if ($this->checkAttrExceptions($exceptions)) continue;
$element->removeAttribute($this->attribute);
}
}
$this->data = base64_encode($dom->saveHTML());
}
public function checkAttrExceptions(array $exceptions)
{
foreach ($exceptions as $tag => $attributes) {
if (empty($attributes) || !is_array($attributes)) {
die('Attributes not set!');
}
foreach ($attributes as $attribute) {
if ($tag === $this->tag && $attribute === $this->attribute) {
return true;
}
}
}
return false;
}
}
Если вам нужно добавить дополнительные исключения атрибутов, просто отредактируйте массив $exceptions
. Например, если вы не хотите, чтобы атрибут title
полосы во всех тегах "a" изменял исключения:
$exceptions = array(
'a' => array('href', 'title'),
'img' => array('src')
);