我尝试从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确实有用..
我收到了这个错误:
警告:第19行 C:\ xampp \ htdocs \ proyectos \ radioargenta \ oyentes \ indexprueba.php 中为foreach()提供的参数无效
可以帮帮我吗?
谢谢!
答案 0 :(得分:1)
您必须按如下方式更改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());
}