1

I know that same issues have been discussed many times but I'm really stuck. I am trying to access a part of an HTML DOM tree:

<div class="price widget-tooltip widget-tooltip-tl price-breakdown">
    <strong class="current-price">10€</strong>
</div>

I want to get the value of the node < strong > which would be 10€, so I use the xpath:

//div//strong[contains(@class, 'current-price')]

which works perfectly in Chrome Dev Tools, but not in my PHP script:

// Create DOM object
$dom = new DOMDocument();
@$dom->loadHTML($header['content']);

$xpath = new DOMXPath($dom);

$prices = $xpath->query("//div//strong[contains(@class, 'current-price')]");

I tried different "versions" as suggested here and here (and in many other cases) without success. The problem is that I'm not getting anything as return value, just empty, nothing.

I isolated the issue and can confirm that it happens only when the class selector goes into game, if I use the path without the class selector it works fine (returning many elements).

What am I doing wrong?

Community
  • 1
  • 1
Foufoutos
  • 17
  • 5
  • 1
    I see incorrect quoting on `'current-price"`. Single at the start and double at the end. Is that what your real code looks like? – Michael Berkowski Apr 13 '17 at 17:11
  • Just to add to @MichaelBerkowski's comment, since you are testing the full class, you don't need `contains` at all, since `strong` is a direct child of `div` you don't need the double slash, and ideally you should indicate you want the `text()`, i.e. `//div/strong[@class="current-price")]/text()` – StuartLC Apr 13 '17 at 17:14
  • @MichaelBerkowski No the quoting is correct, it was mistakenly copy-pasted. I don't get a white screen of death, instead I am getting empty values where I should get some prices. – Foufoutos Apr 13 '17 at 17:17
  • @Foufoutos Can you edit your original post to show the correct code with the quoting as you really have it? The way it's posted now is likely to mislead potential answerers – Michael Berkowski Apr 13 '17 at 17:24
  • Yes please edit your code above, I was about to post the same answer. – Bill Hileman Apr 13 '17 at 19:33
  • 1
    https://eval.in/776219 – splash58 Apr 13 '17 at 19:38
  • Like @splash58 demonstrated, it works if fixed. Include an output in you example code, too. At the moment you do not include the part that uses the, so it is possible that your mistake in this part. – ThW Apr 14 '17 at 10:18
  • Thank you for your replies. I found out the reason that is not working. Indeed, the code is right, but for some reason the specific node is not present in the tree until some certain conditions fulfilled. When I was checking the DOM tree from Chrome Dev Tools, the node had already been created, but in the way I am fetching the page right now this is not true. – Foufoutos Apr 14 '17 at 10:26

0 Answers0