开发者

How to return html instead of strings in php dom parser

<?php
    $convert = function($src) {
    return '<div>'.$src.'</div>';
};

$doc = new DOMDocument;
$doc->loadhtml(getHTML());
foo($doc, $convert);
echo "after: ", $doc->savehtml(), "\n\n";


function foo(DOMDocument $doc, $fn) {
    $xpath = new DOMXPath($doc);

    $imgs = array();
    foreach( $xpath->query('/html/body//img') as $n ) {
        $imgs[] = $n;
    }

    foreach($imgs as $n) {
        $txt = $fn($n->getAttribute('src'));
        $div = $doc->createElement('div', $txt);
        $n->parentNode->replaceChild($div, $n);
    }
}

function getHTML() {
return '<html><head><title>...</title></head><body>
    <p>lorem ipsum <img src="a.jpg" alt="img#1"/></p>
    <p>dolor sit amet<img src="b.jpg" alt="img#2"/></p&g开发者_JAVA百科t;
    <div><div><div><img src="c.jpg" alt="img#3" /></div></div></div>
</body></html>';
}

In the above code in the third line doesn't appear as html in the output, it show as the string. How to return a html tag in this program.


Use echo() not return() when printing the HTML


This should do it:

<?php

$doc = new DOMDocument;
$doc->loadhtml(getHTML());
replaceImageTags($doc);
echo "after: ", $doc->savehtml(), "\n\n";

function replaceImageTags(DOMDocument $doc) 
{

    $xpath = new DOMXPath($doc);

    $imgs = array();
    foreach($xpath->query('/html/body//img') as $n ) {
        $imgs[] = $n;
    }

    foreach($imgs as $n) 
    {
        $div = $doc->createElement('div', $n->getAttribute('src'));
        $n->parentNode->replaceChild($div, $n);
    }
}

function getHTML() {
return '<html><head><title>...</title></head><body>
    <p>lorem ipsum <img src="a.jpg" alt="img#1"/></p>
    <p>dolor sit amet<img src="b.jpg" alt="img#2"/></p>
    <div><div><div><img src="c.jpg" alt="img#3" /></div></div></div>
</body></html>';
}

Outputs:

after: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><head><title>...</title></head><body>
    <p>lorem ipsum <div>a.jpg</div></p>
    <p>dolor sit amet<div>b.jpg</div></p>
    <div><div><div><div>c.jpg</div></div></div></div>
</body></html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜