I'm trying to parse blocks of text with html tags, but I have some problems.
<?php
libxml_use_internal_errors(true);
$html = '
<html>
<body>
<div>
Message <b>bold</b>, <s>strike</s>
</div>
<div>
<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>
</div>
</body>
</html>
';
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
$dom->recover = true;
$dom->loadHTML($html);
function getMessages($element, $xpath)
{
$messages = array();
$children = $element->childNodes;
foreach ($children as $child)
{
if(strtolower($child->nodeName) == 'div')
{
// my functions
}
else
if ($child->nodeType == XML_TEXT_NODE)
{
$text = trim(DOMinnerHTML($element));
if($text)
{
$messages[] = array('type' => 'text', 'text' => $text);
}
}
}
return $messages;
}
function DOMinnerHTML($element)
{
$innerHTML = null;
$children = $element->childNodes;
foreach ($children as $child)
{
$tmp_dom = new DOMDocument();
$tmp_dom->appendChild($tmp_dom->importNode($child, true));
$innerHTML .= trim($tmp_dom->saveHTML());
}
return $innerHTML;
}
$xpath = new DOMXPath($dom);
$messagesXpath = $xpath->query("//div");
$messages = array();
$i = 0;
foreach($messagesXpath as $message)
{
$messages[] = getMessages($message, $xpath);
$i++;
if ($i == 2)
break;
}
var_dump($messages);
This code returns the following array:
array(2) {
[0]=>
array(3) {
[0]=>
array(2) {
["type"]=>
string(4) "text"
["text"]=>
string(32) "Message<b>bold</b>,<s>strike</s>"
}
[1]=>
array(2) {
["type"]=>
string(4) "text"
["text"]=>
string(32) "Message<b>bold</b>,<s>strike</s>"
}
[2]=>
array(2) {
["type"]=>
string(4) "text"
["text"]=>
string(32) "Message<b>bold</b>,<s>strike</s>"
}
}
[1]=>
array(2) {
[0]=>
array(2) {
["type"]=>
string(4) "text"
["text"]=>
string(100) "<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>"
}
[1]=>
array(2) {
["type"]=>
string(4) "text"
["text"]=>
string(100) "<span class="how">
<a href="link" title="text">Link</a>, <b> BOLD </b>
</span>"
}
}
}
I want to have the $messages['text'] with html tags (it's OK) were, but the array for some reason, repeated!!!!
I think that's problem in this block
if ($child->nodeType == XML_TEXT_NODE)
{
$text = trim(DOMinnerHTML($element));
if($text)
{
$messages[] = array('type' => 'text', 'text' => $text);
}
}