Fetching First value from nodeValue using DOMDocument in PHP

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts:48

Fetching First value from nodeValue using DOMDocument in PHP

Hi,
I have the following code that uses DOMDocument to get some data from a html string in PHP.

Code: Select all

// string with HTML content
$strhtml = '<div class="dv1">Nr. 123
<div>Website: <span> https://coursesweb.net/ </span></div>
<div>';

// create the DOMDocument object, and load HTML from string
$dom = new DOMDocument();
$dom->loadHTML($strhtml);

$data = '';
// get data from the Div with class 'dv1'
foreach($dom->getElementsByTagName('div') as $el) {
  if($el->getAttribute('class') == 'dv1') {
    $data = $el->nodeValue;
  }
}
echo $data;  // Nr. 123 Website: https://coursesweb.net/    
- I have to get the first part from that div, the value: "Nr. 123", but it is fetching the whole nodeValue of the Div class "dv1".
How can I get the first string from that Div, without the other texts in the whole nodeValue?
Thanks.

MarPlo Posts:186
Hi,
The nodeValue attribute gives you the combined text of all the child nodes.
To get the text value of the first child text node only, use: firstChild->nodeValue.
Change your code to:

Code: Select all

$data = $el->firstChild->nodeValue;