doutuosai3504
doutuosai3504
2018-04-19 10:40

使用PHP解析HTML:获取元素内部的元素[关闭]

已采纳

I have this structure :

<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>

I want to get :

$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" ]
)

I want to get that data into an array, can please tell me how to do that with PHP ?

Thanx

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • donglianjiang9321 donglianjiang9321 3年前

    Try 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);
    
    点赞 评论 复制链接分享