下面的代码从网页上抓取两个值并将它们添加到数组中。我已经能够打印出该阵列的第一行,但我无法完成整个过程。
我认为需要某种循环,但到目前为止我的尝试都没有成功。
我觉得这应该是相当基本的。知道我能做些什么来达到预期的效果吗?
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']);
答案 0 :(得分:2)
您需要以下详细信息才能创建所需的关联数组:
现在,在您的代码中,您需要循环浏览产品网址 - 并且针对每个产品网址,您需要循环浏览产品图片网址列表。这将导致嵌套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);