使用简单 HTML DOM 获取第二个 <table> 和第二个 <td> 的值

Get value of second <table>, and second <td> using Simple HTML DOM

我正在尝试从 shoutcast 歌曲历史 (link) 中获取值。

页面标记有 2 个表,如:

<table>
    <tbody>
      <tr>
        <td>Header Link 1</td>
        <td>Header Link 2</td>
      </tr>
    </tbody>
</table>
<table>
    <tbody>
        <tr> <td>Lengh of song 1</td> </tr> 
        <tr> <td>Song Title 1</td> </tr> 
        <tr> <td>Lengh of song 2</td> </tr> 
        <tr> <td>Song Title 2</td> </tr> 
      </tr>
    </tbody>
</table>

我只需要获取歌名并将其保存在数据库中。

这是我的代码:

<?php
include_once('simple_html_dom.php');

ini_set('display_errors', true);
error_reporting(E_ALL);

$host="localhost";
$username="root";
$password="";
$database="titulos";

mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "No se puede conectar a la base de datos");

$html = file_get_html('http://138.36.236.207:8000/played.html');
$guardardato = "";

// Buscar 
foreach($html->find('table', 2)->find('tr', 2) as $datossc) {
    foreach($datossc->find('td') as $titulo) {

        echo $titulo->plaintext .'<br>';
        $guardardato .= $titulo->plaintext;
    }
}

$guardardato = mysql_real_escape_string($guardardato);
$query = "INSERT INTO data(name) VALUES('$guardardato')";

mysql_query($query) or die(mysql_error());

$html->clear();
unset($html);
?>

sql 过程没问题,但简单的 dom 确实有效..

我收到那个错误:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\proyectos\radioargenta\oyentes\indexprueba.php on line 19

可以帮我吗?

谢谢!

您必须按如下方式更改 for 循环:

foreach($html->find('table', 2)->find('tr') as $datossc) {
    echo $datossc->find('td', 1)->plaintext .'<br>';
    $guardardato .= $datossc->find('td', 1)->plaintext;
}

请注意,输出中也会有 Song Title

此外,您确定要在 $guardardato 中附加所有标题吗?这只会连接标题,例如Song TitleAle Ceberio - LaCuartetera.NetAlcides - Tan bonita pero muy celosaAgrupaciOn Marylin - Agru...。也许你想做的是:

$guardardato = array();

foreach($html->find('table', 2)->find('tr') as $datossc) {
    $title = $datossc->find('td', 1)->plaintext;
    if ($title != 'Song Title') {  
        echo $title .'<br>';
        $guardardato[] = $title;
    }
}

foreach($guardardato as $i) {
    $value = mysql_real_escape_string($i);
    $query = "INSERT INTO data(name) VALUES('" . $value . "')";
    mysql_query($query) or die(mysql_error());
}