Answer the question
In order to leave comments, you need to log in
How to correctly write a function when outputting in an associative xpath array of a request?
It is necessary to transfer the output of the query xpath list as an array. I registered xpath correctly and I can even display a separate result (I commented out the example in the code).
How to fix Notice: Undefined property: DOMNodeList::$nodeValue error?
<?php
$specoffer = "http://www.msk.lenta.com/show/product/92003/";
libxml_use_internal_errors(true);
$doc = new DOMDocument();
libxml_clear_errors();
$doc->loadHTMLFile($specoffer);
$doc->saveHTML();
$doc->preserveWhiteSpace = false;
$xpath = new DOMXPath($doc);
$prices_name = "Цена: ";
$discounts_name = "Цена со скидкой: ";
$goodsnames_name = "Название: ";
$imglinks_name = "Ссылка на изображение: ";
$goodsdesriptions_name = "Описание: ";
$prices_value = $xpath->query("/html/body/div[1]/div/div/div/section/div/div/main/div[2]/div[2]/div[1]/div/span[2]");
$discounts_value = $xpath->query("/html/body/div[1]/div/div/div/section/div/div/main/div[2]/div[2]/div[1]/div/span[1]");
$goodsnames_value = $xpath->query("/html/body/div[1]/div/div/div/section/div/div/main/div[2]/div[2]/h3");
$imglinks_value = $xpath->query("/html/body/div[1]/div/div/div/section/div/div/main/div[2]/div[1]/a/img");
$goodsdesriptions_value = $xpath->query("/html/body/div[1]/div/div/div/section/div/div/main/div[2]/div[2]/p[1]");
$arr = array(
$prices_name => $prices_value,
$discounts_name => $discounts_value,
$goodsnames_name => $goodsnames_value,
$imglinks_name => $imglinks_value,
$goodsdesriptions_name => $goodsdesriptions_value
);
foreach($arr as $key => $value)
{
echo $key . $value->nodeValue . "<br />";
}
// Рабочий вариант
// foreach ($prices_value as $price) {
// echo "Цена: {$price->nodeValue} <br>";
// }
Answer the question
In order to leave comments, you need to log in
To get a single value after an xpath query, you need to use the item() method.
That is, conditionally:
$prices_value = $xpath->query("//div/span[2]");
if($prices_value !== FALSE && $prices_value->length > 0)
echo $prices_value->item(0)->nodeValue; // тут ваше значение
$prices_value = $xpath->query('//div/span');
if($prices_value !== FALSE && $prices_value->length > 0)
{
foreach($items as $item)
echo $item->nodeValue;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question