views:

64

answers:

2

Hi guys

This is my example script:

$html = <<<HTML
<div class="main">
    <div class="text">
    Capture this text 1
    </div>
    <div class="date">
    May 2010
    </div>
</div>
<div class="main">
    <div class="text">
    Capture this text 2
    </div>
    <div class="date">
    June 2010
    </div>
</div>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);


$tags = $xpath->query('//div[@class="main"]');
foreach ($tags as $tag) {
    print_r($tag->nodeValue."\n");
}

This will out put:

Capture this text 1 May 2010
Capture this text 2 June 2010 

But I need it output:

<div class="text">
Capture this text 2
</div>
<div class="date">
June 2010
</div>

Or atleast be able to do something like this in my foreach loop:

$text = $tag->query('//div[@class="text"]')->nodeValue;
$date = $tag->query('//div[@class="date"]')->nodeValue;
+1  A: 

Well, nodeValue will give you the node's value. You want what's commonly called outerHTML

echo $dom->saveXml($tag);
Gordon
Combine this one with a smidgin of JapanPro's answer as to `innerHTML`, and we could have `$result = '';foreach($tag->childNodes as $tag) $result.=$dom->saveXML($tag);` with the original XPath.
Wrikken
A: 

try this

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$tags = $xpath->query('//div[@class="main"]');

foreach ($tags as $tag) {
    $innerHTML = '';

    $children = $tag->childNodes;
    foreach ($children as $child) {
        $tmp_doc = new DOMDocument();
        $tmp_doc->appendChild($tmp_doc->importNode($child,true));       
        $innerHTML .= $tmp_doc->saveHTML();
    }

    var_dump(trim($innerHTML));
}

-Pascal MARTIN

JapanPro
why voted down , without testing code. leave some feedback as well while voting down.
JapanPro