1

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?

2
  • most likely its a collection of classes, point to the first element, ->find('div.lyrics, 0'), mind the second argument, then echo Commented Apr 17, 2017 at 22:30
  • @Ghost thanks, that worked. Commented Apr 17, 2017 at 22:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

var_dump will be useful in the future. I'm not too familiar with PHP so that would have saved me a bit of time. The comment Ghost left already solved my problem but since this is an answer I'll mark it as correct.
That's not quite it. find always returns an array unless you use the second argument. It's a confusing thing you have to get used to. Also, don't use var_dump, you'll see why not if you try it.
@pguardiario Thanks for the info. I do see why not to use var_dump now lol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.