Jerome のソリューションを拡張する関数をいくつか作成しました。問題は、画像を変更するために、docx ファイル内の参照名を知る必要があることでした。これは、平均的なユーザーにとっては見つけるのが難しい場合があります (docx を「解凍」して、手動で画像を見つける必要があります)。
私のソリューションでは、代替テキスト (通常の形式である必要があります: ${abc} ) で写真を参照できるようになるため、プレースホルダーの写真に単語がどのように名前を付けるかを知る必要はありません。変数で十分です。代替テキストを追加する方法についてのリンクは次のとおりです: http://accessproject.colostate.edu/udl/modules/word/tut_alt_text.php?display=pg_2
TemplateProcessor.php のみを変更しました
最初にこれをクラスに追加します。
/**
* Content of document rels (in XML format) of the temporary document.
*
* @var string
*/
private $temporaryDocumentRels;
コンストラクター関数 (パブリック関数 __construct($documentTemplate)) は最後に拡張する必要があります。これを追加:
$this->temporaryDocumentRels = $this->zipClass->getFromName('word/_rels/document.xml.rels');
$this->temporaryDocumentRels を使用して、document.xml.rels から内容を読み取ることができるようになりました。
Jerome のコードを保持します。
/**
* Set a new image
*
* @param string $search
* @param string $replace
*/
public function setImageValue($search, $replace){
// Sanity check
if (!file_exists($replace))
{
return;
}
// Delete current image
$this->zipClass->deleteName('word/media/' . $search);
// Add a new one
$this->zipClass->addFile($replace, 'word/media/' . $search);
}
この関数は、ラベル付けした画像の rId を返します。
/**
* Search for the labeled image's rId
*
* @param string $search
*/
public function seachImagerId($search){
if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
$search = '${' . $search . '}';
}
$tagPos = strpos($this->temporaryDocumentMainPart, $search);
$rIdStart = strpos($this->temporaryDocumentMainPart, 'r:embed="',$tagPos)+9;
$rId=strstr(substr($this->temporaryDocumentMainPart, $rIdStart),'"', true);
return $rId;
}
rId であることがわかっている場合、これは画像のファイル名を返します。
/**
* Get img filename with it's rId
*
* @param string $rId
*/
public function getImgFileName($rId){
$tagPos = strpos($this->temporaryDocumentRels, $rId);
$fileNameStart = strpos($this->temporaryDocumentRels, 'Target="media/',$tagPos)+14;
$fileName=strstr(substr($this->temporaryDocumentRels, $fileNameStart),'"', true);
return $fileName;
}
TemplateProcessor.php の変更が完了しました。
これを呼び出すことで画像を置き換えることができます:
$templateProcessor->setImageValue($templateProcessor->getImgFileName($templateProcessor->seachImagerId("abc")),$replace);
次のように呼び出す関数を TemplateProcessor.php で作成することもできます。
public function setImageValueAlt($searchAlt, $replace){
$this->setImageValue($this->getImgFileName($this->seachImagerId($searchAlt)),$replace);
}