You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于搜索筛选并仅打印指定艺人的Spotify榜单数据

解决Spotify Charts表格筛选特定艺人行的问题

没问题,我来帮你搞定这个需求!你的代码已经能成功读取Spotify Charts的表格数据了,现在只需要加个行过滤逻辑,就能只打印包含指定艺人(比如Post Malone)的行。

核心思路

Spotify Charts的表格里,艺人名称是包含在第三个<td>元素里的(和歌曲名在一起),所以我们只需要在循环中检查当前行的对应位置是否包含目标艺人名称,符合条件的才保留/打印。

修改后的完整代码

这里我提供两种修改方案,你可以选适合自己的:

方案1:在打印阶段过滤(改动最小)

直接在打印表格的循环里加判断,只输出符合条件的行:

<?php
include_once('../simple_html_dom.php');
$html = file_get_html('https://spotifycharts.com/regional/us/daily/latest');
$table = $html->find('table', 0);
$rowData = array();

foreach($table->find('tr') as $row) {
    $onerow = array();
    foreach($row->find('td') as $cell) {
        $onerow[] = $cell->plaintext;
    }
    $rowData[] = $onerow;
}

echo '<table>';
foreach ($rowData as $row => $tr) {
    // 关键:检查当前行的艺人区域是否包含目标名称,这里用strpos判断存在性
    if (strpos(trim($tr[2]), 'Post Malone') !== false) {
        echo '<tr>';
        foreach ($tr as $td) echo '<td>' . $td .'</td>';
        echo '</tr>';
    }
}
echo '</table>';
?>

方案2:在数据收集阶段过滤(更高效)

提前过滤掉不需要的行,减少后续循环的处理量:

<?php
include_once('../simple_html_dom.php');
$html = file_get_html('https://spotifycharts.com/regional/us/daily/latest');
$table = $html->find('table', 0);
$rowData = array();

foreach($table->find('tr') as $row) {
    $onerow = array();
    foreach($row->find('td') as $cell) {
        $onerow[] = $cell->plaintext;
    }
    // 关键:收集数据时就过滤,只保留包含目标艺人的行
    if (strpos(trim($onerow[2]), 'Post Malone') !== false) {
        $rowData[] = $onerow;
    }
}

echo '<table>';
foreach ($rowData as $row => $tr) {
    echo '<tr>';
    foreach ($tr as $td) echo '<td>' . $td .'</td>';
    echo '</tr>';
}
echo '</table>';
?>

关键细节说明

  • strpos(trim($tr[2]), 'Post Malone') !== false:这里用strpos判断字符串是否存在,trim()是为了去除文本里的多余空格或换行,避免匹配失败;用!== false而不是!=,是为了避免艺人名称刚好在文本开头(此时strpos返回0,会被!= false误判为不存在)。
  • 如果发现$tr[2]不对,可以临时打印$rowData看看数组结构,确认艺人名称所在的索引位置(比如可能是$tr[3],取决于页面结构的细微变化)。

内容的提问来源于stack exchange,提问作者Maya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:31:12