输出多于数组第一行的内容


Printing more than the first row of array

下面的代码从网页中抓取两个值并将它们添加到数组中。我只能输出数组的第一行但不能输出整个数组

我假设需要某种循环,但我的尝试到目前为止还没有成功。

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

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 -对于每个产品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);