Alex
Alex

Reputation: 1

PHP Simple HTML Dom Parser code is not working. Output is blank

I was trying to scrape the data from "non-secured" url that is using 'http' instead of 'https'.
Here is the code

function display_html_info2() {
  $html = file_get_contents('http://adamsonsgroup.com/goldrates/');
  $dom = new DOMDocument();
  $dom->loadHTML($html);
  $xpath = new DOMXPath($dom);
  $h3_element = $xpath->query('/html/body/div[1]/div/div[1]/div[3]/div/div[1]/table/tbody/tr[2]/td[1]/h3')->item(0);
  return $h3_element->nodeValue;
}
add_shortcode('shortcode_name2', 'display_html_info2');

I have also tried using XPath

//*[@id="myCarousel"]/div/div[1]/div[3]/div/div[1]/table/tbody/tr[2]/td[1]/h3

In both the cases, it shows blank output. Means No Value.
This is the tag whose value I am trying to show.
Please let me know how this will work.
I have included the html_dom_parser.php

I tried the above mentioned code but it is giving No Value as Output. Instead, it is showing blank space where is use shortcode [shortcode_name2] to show output of the above code.

I have tried @Pinke Helga method but does not work for me. That's what I did

declare(strict_types = 1);
function display_html_info2() {
  $html = file_get_contents('http://adamsonsgroup.com/goldrates/');

  if (!is_string($html)) {
    return 'Error: Could not retrieve the HTML content.';
  }

  $dom = new DOMDocument();
  $dom->loadHTML($html);
  $xpath = new DOMXPath($dom);
  $h3_element = $xpath->query('//*[@id="myCarousel"]/div/div[1]/div[3]/div/div[1]/table/tr[2]/td[1]/h3')->item(0);
  return $h3_element->nodeValue;
}
echo display_html_info2();
add_shortcode('shortcode_name2', 'display_html_info2');

And that's what I got. "Error: Could not retrieve the HTML content."

Upvotes: 0

Views: 153

Answers (1)

Pinke Helga
Pinke Helga

Reputation: 6682

It looks as you have generated the xpath expression from browser dev-tools. The browser extends some HTML. There is no <tbody> in the original source.

Use the xpath expression //*@id="myCarousel"]/div/div[1]/div[3]/div/div[1]/table/tr[2]/td[1]/h3

Complete code:

<?php declare(strict_types = 1);
function display_html_info2() {
  $html = file_get_contents('http://adamsonsgroup.com/goldrates/');
  $dom = new DOMDocument();
  $dom->loadHTML($html);
  $xpath = new DOMXPath($dom);
  $h3_element = $xpath->query('//*[@id="myCarousel"]/div/div[1]/div[3]/div/div[1]/table/tr[2]/td[1]/h3')->item(0);
//  var_dump($h3_element);
  return $h3_element->nodeValue;
}

echo display_html_info2(); // DEBUG output

Current result:

21.898 OMR

Upvotes: 1

Related Questions