dp20011 2019-04-09 17:46
浏览 29
已采纳

使用PHP从网站保存HTML标记<td>数据

I am trying to save the song title from the URL: https://onlineradiobox.com/us/977todayshits/playlist

I used the below code to fetch data

$html = file_get_contents("https://onlineradiobox.com/us/977todayshits/playlist");
    $matches = array();
    $output = preg_match_all('/<table class="tablelist-schedule" role="log">(.*?)<\/table>/s', $html, $matches,PREG_SET_ORDER );
    echo "<pre>";
    print_r($matches);
    echo "</pre>";

The result from the above Code:

Live    Mark Ronson - Nothing Breaks Like a Heart (feat. Miley Cyrus)
10:41   Camila Cabello - Consequences
10:38   Imagine Dragons - It's Time
10:34   Panic! at the Disco - High Hopes
10:31   Selena Gomez - Hands to Myself

This code gets the data but I don't know how will I save the 2nd td tag value in a table. It is not necessary that 2nd td will be a link when it is not linked then there is no class defined in td tag.

  • 写回答

1条回答 默认 最新

  • dqr3883 2019-04-09 18:15
    关注

    As @Denis V said, don't use RegEx to parse html/xml content, use a proper lib for this, like LibXML...

    Example:

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML(file_get_contents('https://onlineradiobox.com/us/977todayshits/playlist'));
    
    $xPath = new DOMXPath($dom);
    
    $nodes = $xPath->query('//table[@class="tablelist-schedule"]/tbody/tr/td[2]');
    
    foreach ($nodes as $node) {
        echo $node->textContent . "
    ";
    }
    

    Prints...

    Pitbull - Time Of Our Lives (feat. Ne Yo)

    Ellie Goulding - Close to Me (x Diplo feat. Swae Lee)

    Post Malone & Swae Lee - Sunflower

    Why Don't We - 8 Letters

    NF - Lie

    ... list too long...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?