php - 打印超出数组第一行的内容

标签 php arrays foreach

下面的代码从网页中抓取两个值并将它们添加到数组中。我已经能够打印该数组的第一行,但我无法获取整个内容。

我认为需要某种循环,但到目前为止我的尝试尚未成功。

我觉得这应该是相当基本的。知道我可以做什么来达到预期的结果吗?

if(!empty($html)) {

    $doc->loadHTML($html);
    libxml_clear_errors(); // remove errors for yucky html
    $xpath = new DOMXPath($doc);

    /* FIND LINK TO PRODUCT PAGE */

    $products = array();

    $row = $xpath->query("$product_location");

    if ($row->length > 0) {

        foreach ($row as $location) {

            $products['product_url'] = $product_url_root.$location->getAttribute('href');
            $products['shop_name'] = $shop_name;

            $row = $xpath->query($photo_location);

            /* FIND LINK TO IMAGE */

            if ($row->length > 0) {

                foreach ($row as $location) {

                $products['photo_url'] = $photo_url_root.$location->getAttribute('src');

                }
            }
        }

            print_r($products);

    }
}

编辑

我应该说我希望得到这种格式的数组:

Array (
    [0] {product_url => 123, shop_name => name, photo_url => abc}, 
    [1] {product_url => 456, shop_name => name, photo_url => def}, 
    [2] {product_url => 789, shop_name => name, photo_url => ghi}, 
    )

计划最终能够使用以下代码代替 print_r($products) 来创建 XML 文件:

$item = $channel->addChild("item");
$item->addChild("product_url", $entry['product_url']);
$item->addChild("shop_name", $entry['shop_name']);
$item->addChild("photo_url", $entry['photo_url']);

最佳答案

您需要以下详细信息来创建所需的关联数组:

  • 产品网址
  • 店铺名称
  • 产品图片网址

现在,在您的代码中,您将循环访问产品 URL,并且对于每个产品 URL,您将循环访问产品图片 URL 列表。这将导致嵌套 foreach 内的代码被执行 n^2 次。你不希望这样。

以下是构建循环的方式:

/* Create an array containing products */
if ($row->length > 0)
{            
    foreach ($row as $location)
    {
        $product_urls[] = $product_url_root . $location->getAttribute('href');
    }
}
$imgs = $xpath->query($photo_location);

/* Create an array containing the image links */
if ($imgs->length > 0)
{            
    foreach ($imgs as $img)
    {
        $photo_url[] = $photo_url_root . $img->getAttribute('src');
    }
}


$result = array();

/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
    $result[] = array(
        'product_url' => $product_url,
        'shop_name' => $shop_name,
        'photo_url' => $photo_url[$i]
    );
}

print_r($result);

关于php - 打印超出数组第一行的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22427785/

相关文章:

javascript - AngularJS 数组过滤器不起作用

perl - 如何在Perl中的嵌套列表运算符中区分$ _?

c++ - [](){} 构造在 C++ 中意味着什么?

php - 第一个具有多个 where 子句的左连接(左表)

php - php和boost库IPC如何通信?

arrays - SwiftUI:如何循环遍历 "For Each"内的 Int 数组

PowerShell:如果未找到字符串,则会出现不必要的错误

php - 按年份对串联数据值进行分组

php - 从数据库 TIMESTAMP PHP 输出日期和时间

javascript - 颜色框帖子表单值