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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题