首页 > 解决方案 > 简单的 Html Dom 解析表格内的多个图像

问题描述

我有这个代码:

    require('simple_html_dom.php');
    $xurl=('https://example.com/pics/flower.php');
    $html = file_get_html($xurl);
    $articles = [];
    $i = 0;

   foreach ($html->find('div.gallery-a -> *') as $article) {
   if ($i > 22) {
                break;
        }

    $title = $html->find('div.gallery-a -> table -> tr.*[id] -> td -> a', $i)->plaintext;
    $url = $html->find('div.gallery-a -> table -> tr.*[id] -> td -> a', $i)->href;
    $images = $html->find('div.gallery-a -> table ->td -> table -> tr -> img',$i)->src;

    $item['Title'] = $title;
    $item['link'] = $url;
    $item['image'] = $images;

    $articles[] = $item;
    $i++;
    }


    $result = json_encode($articles, JSON_PRETTY_PRINT);        

    header('Access-Control-Allow-Origin: *');
    header('Content-type: Application/JSON');
    echo $result;

这是要解析的 html 代码:https ://pastebin.com/uj4YHiHt

我试图用 php simple html dom 从一个站点抓取数据,该站点在其源代码上使用的类或 id 非常少,所以我很难找到正确的代码来获得我想要的结果

我能够管理 2 个具有正确结果的项目(Titleurl ),但我对表格内的图像项目有困难。这是我尝试使用循环获取图像的结果。

[
    {
        "Title": "Tulip flower under the rainbow",
        "link": "\/gallery.php?id=345",
        "image": "https://example.com/images/tulip1.jpg"
    },
    {
        "Title": "Red Rose flower",
        "link": "\/gallery.php?id=346",
        "image": "https://example.com/images/tulip2.jpg"
    },

预期结果

[
    {
        "Title": "Tulip flower under the rainbow",
        "link": "\/gallery.php?id=345",
        "image1": "https://example.com/images/tulip1.jpg"
        "image2": "https://example.com/images/tulip2.jpg"
        "image3": "https://example.com/images/tulip3.jpg"
        "image4": "https://example.com/images/tulip4.jpg"
    },
    {
        "Title": "Red Rose flower",
        "link": "\/gallery.php?id=346",
        "image1": "https://example.com/images/rose1.jpg"
        "image2": "https://example.com/images/rose2.jpg"
        "image3": "https://example.com/images/rose3.jpg"
        "image4": "https://example.com/images/rose4.jpg"
    },

请帮忙。

标签: phpdom

解决方案


推荐阅读