Search code examples
phpparsingweb-scrapingsimple-html-dom

PHP Simple HTML DOM Parser returning div as an array


I'm using PHP and simple HTML DOM Parser to try and grab song lyrics from a website. The song lyrics are held in a div with the class "lyrics". Here's the code I'm using to try and grab the div and display it. Currently it only returns "Array" onto my webpage. When I jsonify the array I can see that the array is empty.

<?php
include('simple_html_dom.php');
$data = file_get_contents("https://example.com/songlyrics");
$html = str_get_html($data);
$lyr = $html->find('div.lyrics');
echo $lyr;
?>

I know that the Simple HTML Dom Parser is being included correctly, and I have no problem displaying the full webpage when I echo $html with some small changes to the code, however I can't seem to echo just this div. Is there something wrong with my code? Why is $lyr returning an array?


Solution

  • There's nothing wrong with your code.

    Why is $lyr returning an array?

    It's because a class is considered to be used multiple times. If you var_dump($lyr) instead, you should see all the div-elements found with that class name.

    You can either echo $lyr[0] or you can $html->find('div.lyrics',0) to select a specific div element.