From 0425a25cdbbb820eded9473f4026ef32db57baa4 Mon Sep 17 00:00:00 2001 From: troosan Date: Thu, 25 Jan 2018 23:24:21 +0100 Subject: [PATCH] Add parsing of HTML links --- samples/Sample_26_Html.php | 2 ++ src/PhpWord/Shared/Html.php | 23 +++++++++++++++++++++++ tests/PhpWord/Shared/HtmlTest.php | 13 +++++++++++++ 3 files changed, 38 insertions(+) diff --git a/samples/Sample_26_Html.php b/samples/Sample_26_Html.php index 99a35f9c..69d9d131 100644 --- a/samples/Sample_26_Html.php +++ b/samples/Sample_26_Html.php @@ -10,6 +10,8 @@ $html = '

Adding element via HTML

'; $html .= '

Some well formed HTML snippet needs to be used

'; $html .= '

With for example some1 inline formatting1

'; +$html .= '

A link to Read the docs

'; + $html .= '

Unordered (bulleted) list:

'; $html .= ''; diff --git a/src/PhpWord/Shared/Html.php b/src/PhpWord/Shared/Html.php index fd0bd545..0f5f446a 100644 --- a/src/PhpWord/Shared/Html.php +++ b/src/PhpWord/Shared/Html.php @@ -142,6 +142,7 @@ class Html 'li' => array('ListItem', $node, $element, $styles, $data, null, null), 'img' => array('Image', $node, $element, $styles, null, null, null), 'br' => array('LineBreak', null, $element, $styles, null, null, null), + 'a' => array('Link', $node, $element, $styles, null, null, null), ); $newElement = null; @@ -643,4 +644,26 @@ class Html { $element->addTextBreak(); } + + /** + * Parse link node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + */ + private static function parseLink($node, $element, &$styles) + { + $target = null; + foreach ($node->attributes as $attribute) { + switch ($attribute->name) { + case 'href': + $target = $attribute->value; + break; + } + } + self::parseInlineStyle($node, $styles['font']); + + return $element->addLink($target, $node->textContent, $styles['font'], $styles['paragraph']); + } } diff --git a/tests/PhpWord/Shared/HtmlTest.php b/tests/PhpWord/Shared/HtmlTest.php index 9c4cfd55..6122924f 100644 --- a/tests/PhpWord/Shared/HtmlTest.php +++ b/tests/PhpWord/Shared/HtmlTest.php @@ -341,4 +341,17 @@ class HtmlTest extends \PHPUnit\Framework\TestCase $this->assertStringMatchesFormat('%Smso-position-horizontal:right%S', $doc->getElementAttribute($baseXpath . '[1]/w:pict/v:shape', 'style')); $this->assertStringMatchesFormat('%Smso-position-horizontal:left%S', $doc->getElementAttribute($baseXpath . '[2]/w:pict/v:shape', 'style')); } + + public function testParseLink() + { + $phpWord = new \PhpOffice\PhpWord\PhpWord(); + $section = $phpWord->addSection(); + $html = '

link text

'; + Html::addHtml($section, $html); + + $doc = TestHelperDOCX::getDocument($phpWord, 'Word2007'); + + $this->assertTrue($doc->elementExists('/w:document/w:body/w:p/w:hyperlink')); + $this->assertEquals('link text', $doc->getElement('/w:document/w:body/w:p/w:hyperlink/w:r/w:t')->nodeValue); + } }