I'm trying to use eval() to execute a string of SimpleHTML. I'm fully aware of the dangers of eval() and will not be using any user input for the string that is to be executed.
$my_data = str_get_html('<html><body><a href=\"https://www.example.com\">Hello!</a></body></html>');
$str = '$my_data->find(\'a\', 0)->attr[\'href\']';
eval ("\$str = \"$str\";");
echo $str;
The above code doesn't execute, and after echoing $str, I get:
('a', 0)->attr['href']
What happened to the first part of the $str string (i.e. $my_data->find )? How can I actually execute the code from the $str string?
The code you are passing to the eval is wrong. You are trying to eval the following code:
$str = "$my_data->find('a', 0)->attr['href']";
The correct code would be:
$str = $my_data->find('a', 0)->attr['href'];
Or:
$str = "{$my_data->find('a', 0)->attr['href']}";
This code works:
<?php
require __DIR__ . '/simplehtmldom_1_9_1/simple_html_dom.php';
$my_data = str_get_html('<html><body><a href=\"https://www.example.com\">Hello!</a></body></html>');
$str = '$my_data->find(\'a\', 0)->attr[\'href\']';
eval ("\$str = $str;");
echo $str;