Skip to content
Advertisement

How to Split the nodevalues on php dom element

i scrape the website, i am getting result of below in single element, i want to split the one by one element.

code:

$dom1 = new DomDocument();
@ $dom1->loadHTML($res1);
$jobview=$dom1->getElementById('test');
foreach($jobview->getElementsByTagName('div') as $divlist){
    echo $test=$divlist->nodeValue; 
}

input:-

<strong>Testcontent</strong> <br><br> "Test" <br></br> 

Current output:-

Testcontent Test 

expecting output:-

array[0]=>Testcontent [1]=>Test 

Advertisement

Answer

Each of the text parts is a part of the <div> tag, so this code just assumes that you want the text from each direct child not and adds it to an array in the loop using []

$output = [];
foreach($jobview->getElementsByTagName('div') as $divlist){
    foreach ( $divlist->childNodes as $node )   {
        if ( trim($node->textContent) ) {
            $output[] = $node->textContent;
        }
    }
}
print_r($output);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement