Php 打印多于数组的第一行

Php 打印多于数组的第一行,php,arrays,foreach,Php,Arrays,Foreach,下面的代码从网页中提取两个值,并将它们添加到数组中。我已经能够打印出数组的第一行了,但是我无法得到全部内容 我认为需要某种循环,但到目前为止我的尝试都没有成功 我觉得这应该是相当基本的。你知道我能做些什么来达到预期的效果吗 if(!empty($html)) { $doc->loadHTML($html); libxml_clear_errors(); // remove errors for yucky html $xpath = new DOMXPath($d

下面的代码从网页中提取两个值,并将它们添加到数组中。我已经能够打印出数组的第一行了,但是我无法得到全部内容

我认为需要某种循环,但到目前为止我的尝试都没有成功

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

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);

谢谢你的回复。在第一个foreach循环中,$products['product\u url']和$products['shop\u name']也是这样吗?我已经更改了它,现在我得到了这个结果,这不是理想的结果:@user3423062:Add
完成之前添加标签,看起来它是按每个属性而不是每个元素对它们进行分组,如果你明白我的意思的话。(刚刚看到你的编辑,非常有用地解释了我最初的错误是什么,谢谢。)看看我的编辑,了解我正在尝试的achieve@user3423062:我已经更新了我的答案。这有用吗?