使用PHP解析HTML:获取元素内部的元素

时间:2018-04-19 10:40:50

标签: php html parsing dom

我有这个结构:

<div id="posts">
<li><a class="title" href="link1">Title 1</a><span class="hour">12:43</span></li>
<li><a class="title" href="link2">Title 2</a><span class="hour">04:43</span></li>
<li><a class="title" href="link3">Title 3</a><span class="hour">15:43</span></li>
<li><a class="title" href="link4">Title 4</a><span class="hour">18:43</span></li>
</div>

我想得到:

$array = ( 
[title => "Title 1", link => "Link1", Date => "Date 1" ], 
[title => "Title 2", link => "Link2", Date => "Date 2" ],
[title => "Title 3", link => "Link3", Date => "Date 3" ],
[title => "Title 4", link => "Link4", Date => "Date 4" ]
)

我想将数据转换为数组,请告诉我如何使用PHP做到这一点?

感谢名单

1 个答案:

答案 0 :(得分:1)

尝试PHP Simple HTML DOM Parser

// Create DOM from URL
$html = file_get_html('http://slashdot.org/');

// Find all article blocks
foreach($html->find('div.article') as $article) {
    $item['title']     = $article->find('div.title', 0)->plaintext;
    $item['intro']    = $article->find('div.intro', 0)->plaintext;
    $item['details'] = $article->find('div.details', 0)->plaintext;
    $articles[] = $item;
}

print_r($articles);