0

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?

2
  • 1
    Why do you think you have to use the evil eval() at all? Commented Jun 2, 2020 at 19:05
  • Maybe I don't, but I'm not sure what other options I have. Each of my 'selectors' that will be within the $str string will be completely different in format. Some will have parameters for the find method, some won't. Some will be using CSS selectors while others will use more SimpleHTML DOM syntax. Commented Jun 2, 2020 at 19:09

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

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.