PHP DOM遍历另一个元素内的元素

时间:2013-02-09 09:54:35

标签: php dom web

我必须从网站收集一些数据。我的数据被包装为div s。在每个div中都有一个标题标签。我需要在这些标题标签内获取文本。如何做到这一点。 我写了以下代码。我必须申请什么修改才能完成任务

<?php
$str = '';
$page =  file_get_contents('http://www.sarkari-naukri.in/');
$dom = new DOMDocument();
$dom->loadHTML($page);
$divs = $dom->getElementsByTagName('div');
$i = 0;
$len = $divs->length;
while($i<$len) {
    $div = $divs->item($i++);
    $id = $div->getAttribute('id');
    if(strpos($id,'post-') !== false ) {
           // i need to get text inside title tag inside this div
        $title ='';//title should be stored here
        $str = $str.$title;
    }
}
echo $str;

示例HTML

<body>
    <div id = 'post-1'>
         <title>title 1</title>
    </div>
    <div id = 'post-2'>
         <title>title 2</title>
    </div>
    <div id = 'post-3'>
         <title>title 3</title>
    </div>
</body>

2 个答案:

答案 0 :(得分:2)

以下PHP DOMDOcument代码:

$id = $div->getAttribute('id');
if (strpos($id,'post-') !== false) {

可以Xpath 1.0表示Xpath string functionDocs

//div[contains(@id, 'post-')]

阅读:任何div元素,其id属性包含字符串post-。根据Xpath的规则,您可以进一步扩展表达式,例如selectinig所有那些的标题子项:

//div[contains(@id, 'post-')]/title

答案 1 :(得分:1)

您可以使用xpath查询来检索标题信息:

$xml = "<body>
    <div id = 'post-1'>
         <title>title 1</title>
    </div>
    <div id = 'post-2'>
         <title>title 2</title>
    </div>
    <div id = 'post-3'>
         <title>title 3</title>
    </div>
</body>";

$str = '';

$doc = new DOMDocument;
$doc->loadHTML($xml);

$xpath = new DOMXPath($doc);

$entries = $xpath->query('//body/div/title');
foreach ($entries as $entry) {
    $str .= $entry->nodeValue;
}

var_dump($str);

Live demo