A
A
ayapergenov2016-10-10 10:54:01
PHP
ayapergenov, 2016-10-10 10:54:01

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

1 answer(s)
I
Ilya, 2016-10-10
@ayapergenov

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; // тут ваше значение

The only way to avoid using item() is if you iterate the results of query(), for example:
$prices_value = $xpath->query('//div/span');
if($prices_value !== FALSE && $prices_value->length > 0)
{
   foreach($items as $item)
      echo $item->nodeValue;
}

And this is already a little beyond the scope of your question, but I would recommend shortening the xpath expressions in query (). I understand that you copied them from Firebug or another webdev tool, but in your case, a minimal change in the donor layout will cause your xpath queries to fail.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question