php简单的html dom返回数组?

时间:2014-07-24 07:20:25

标签: php mysqli simple-html-dom

我尝试使用简单的HTML DOM php脚本创建一个应用程序,但我现在正在使用它 - 希望你可以提供帮助。

目的是从mySQL数据库中读取产品编号,将这些数字与url常量连接起来,然后将这个结果网站解析为特定的类。然后应将结果打印到屏幕上。

我的问题是脚本只返回函数数组的第一个结果,我尝试过一些东西,比如尝试调用$ prices-> children [4],但似乎没有任何帮助。

当我用url触发函数get_prices_array()时,它会带回多个结果 - >但是当我在while循环中返回它时,它只返回数组中的第一个结果。

继承我的代码,希望你能指出我正确的方向!

谢谢!

<?php

include('simple_html_dom.php');

function get_prices_array($url) {

    $x = file_get_html($url);
    foreach ($x->find('span.price')as $dom) {
        $y = $dom->outertext;
        return $y;
    }
    $x->clear();
}

$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}

$result = mysqli_query($con, "SELECT * FROM articles");

while ($row = mysqli_fetch_array($result)) {
    $constant = '***';
    $prices = get_prices_array($constant . $row["product_number"]);
    echo $row["product_number"] . " - " . $prices . '<br />';
}

mysqli_close($con);
?>

//编辑//

我更改了函数get_prices_array()以遍历每个跨度价格类并将结果添加到数组中,然后从函数返回该数组。然后将数组的前5个结果存储到变量中并添加到返回字符串中。谢谢你的帮助!

<?php

include('simple_html_dom.php');

function get_prices_array($url) {

$x = file_get_html($url);
$y = array();
foreach ($x->find('span.price')as $dom) {
    $x = ($dom->outertext);
    $y[] = $x;
}
return $y;
//$x->clear();
}

$con = mysqli_connect("localhost", "***", "***", "***");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}

$result = mysqli_query($con, "SELECT * FROM articles");

while ($row = mysqli_fetch_array($result)) {
$constant = '***';
$prices = get_prices_array($constant . $row["product_number"]);
$pos1 = $prices[0];
$pos2 = $prices[1];
$pos3 = $prices[2];
$pos4 = $prices[3];
$pos5 = $prices[4];
echo $row["product_number"] . " - " . $pos1 . " - " . $pos2 . " - " . $pos3 . " - " .   $pos4 . " - " . $pos5 .'<br />';
}

mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:0)

我认为问题是因为在函数get_prices_array($ url)的foreach循环中使用了返回。

它只执行一次foreach循环。如果在循环内没有条件返回,则没有循环的含义。

相关问题