Home » Php » php – add link to text to exist docx in phpword

php – add link to text to exist docx in phpword

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying add link to text in exist docx with phpword. In documentation i found example like:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$textrun->addLink('https://github.com/PHPOffice/PHPWord', 'PHPWord', 'Link');

but I open doc and founding the desired text inside Section-inside Elements.
Can i remove this element text and create element link? Maybe there are some other ways? thanks!

$i = 0;
$objReader = \PhpOffice\PhpWord\IOFactory::createReader('Word2007');
$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
foreach($phpWord->getSections() as $section) {
    foreach($section->getElements() as $e) {
        if ($e instanceof \PhpOffice\PhpWord\Element\Table) {
            foreach ($e->getRows() as $row) {
                foreach ($row->getCells() as $cell) {
                    foreach ($cell->getElements() as $element) {
                        if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak) {
                            /////
                        } else {
                            foreach ($element->getElements() as $key => $el) {
                                if ($el instanceof \PhpOffice\PhpWord\Element\Text) {
                                    if ($id_first_paragraph == $i && $el->getElementIndex() == $idFirstElement) {
                                        /* add link in text */
                                    }
                                }
                            }
                        }
                        $i++;
                    }
                }
            }
        }
    }
}
How to&Answers: