DomDocument php提取信息和图像


DomDocument php extract info and images

你好,我在使用DomDocument时遇到了问题。我需要做一个脚本,从具有特定 id 的表中提取所有信息。

所以我做到了:

$link = "WEBSITE URL";
$html = file_get_contents($link);
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$context_nodes = $xpath->query('//table[@id="news"]/tr[position()>0]/td');

所以我得到了所有的<td>和信息,但问题是脚本没有提取<img>标签。如何提取表格的所有信息(文本或图像 html 标签)?

我要从中提取信息的 html 代码是:

<table id="news" width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td width="539" height="35"><span><strong>Info to Extract</strong></span></td>
    </tr>
    <tr>
        <td height="35" class="texto10">Martes, 02 de Octubre de 2012  | Autor: Trovert"  rel="author"></a></td>
    </tr>
    <tr>
        <td height="35" class="texto12Gris"><p><strong>Info To extract</strong></p>
            <p><strong>&nbsp;</strong></p>
            <p><strong>Casa de Gobierno: (a 9 cuadras del hostel)</strong></p>
            <img title="title" src="../images/theimage.jpg" width="400" height="266" />
        </td>
    </tr>
</table>

这就是我迭代提取元素的方式:

foreach ($context_nodes as $node) {
    echo $node->nodeValue . '<br/>';
}

谢谢

如果你需要的不仅仅是文本,你必须更加努力,不仅仅是nodeValue/textContent ,而是遍历目标节点 DOM 分支:

function walkNode($node)
{
    $str="";
    if($node->nodeType==XML_TEXT_NODE)
    {
        $str.=$node->nodeValue;
    }
    elseif(strtolower($node->nodeName)=="img")
    {
        /* This is just a demonstration;
         * You'll have to extract the info in the way you want
         * */
        $str.='<img src="'.$node->attributes->getNamedItem("src")->nodeValue.'" />';
    }
    if($node->firstChild) $str.=walkNode($node->firstChild);
    if($node->nextSibling) $str.=walkNode($node->nextSibling);
    return $str;
}

这是一个简单、直接的递归函数。所以现在你可以这样做:

$dom=new DOMDocument();
$dom->loadHTML($html);
$xpath=new DOMXPath($dom);
$tds=$xpath->query('//table[@id="news"]//tr[position()>0]/td');
foreach($tds as $td)
{
    echo walkNode($td->firstChild);
    echo "'n";
}

在线演示
(请注意,我"修复"了你的一点 HTML,因为它似乎无效;也缩进了一点点)

这将输出如下内容:

Info to Extract
Martes, 02 de Octubre de 2012  | Autor: Trovert
Info To extract
            Casa de Gobierno: (a 9 cuadras del hostel)
            <img src="../images/theimage.jpg" />

试试这个....

foreach ($context_nodes as $node) {
echo $doc->saveHTML($node) . '<br/>';
}