0

PHP Simple HTML DOM Parser's way of creating an attribute

file_get_html("http://google.com")->find('body')->bgcolor = '&675432';

on PHP 5.6.13 causes a warning

Creating default object from empty value

.

Is there some way to create an attribute without such a warning without changing the error reporting level or defacing the code as per Creating default object from empty value in PHP? ?

That defacement is having to create an object manually where the object doe not exist, but in the example above, it does.

EDIT: var_dump(file_get_html("http://google.com")->find('body'));

gives

array(1) { [0]=> object(simple_html_dom_node)#18 (9) { ["nodetype"]=> int(1) ["tag"]=> string(4) "body" ["attr"]=> array(1) { ["bgcolor"]=> string(4) "#fff" } ["children"]=> array(6) { [0]=> object(simple_html_dom_node)#19 (9) { ["nodetype"]=> int(1) ["tag"]=> string(6) "script" ["attr"]=> array(0) { } ["children"]=> array(0) { } ["nodes"]=> array(1) { [0]=> object(simple_html_dom_node)#20 (9) { ["nodetype"]=> int(3) ["tag"]=> string(4) "text" ["attr"]=> array(0) { } ["children"]=> array(0) { } ["nodes"]=> array(0) { } ["parent"]=> RECURSION ["_"]=> array(1) { [4]=> string(16) "noise 1007" } ["tag_start"]=> int(0) ["dom":"simple_html_dom_node":private]=> object(simple_html_dom)#1 (23) { ["root"]=> object(simple_html_dom_node)#2 (9) { ["nodetype"]=> int(5) ["tag"]=> string(4) "root" ["attr"]=> array(0) { } ["children"]=> array(2) { [0]=> object(simple_html_dom_node)#3 (9) { ["nodetype"]=> int(6) ["tag"]=> string(7) "unknown" ["attr"]=> array(0) { } ["children"]=> array(0) { } ["nodes"]=> array(0) { } ["parent"]=> RECURSION

Community
  • 1
  • 1
ChrisJJ
  • 2,191
  • 1
  • 25
  • 38

2 Answers2

0

I'm not sure by what you mean by "defacing code" but the answer is in the link you posted.

If $e is not an object, you need to declare it as one. This is done with:

$e = new stdClass()

You could also do $e = (object) []. Which essentially does the same thing, you type cast a blank array to an object.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • Thanks, but the answer is not in the link I posted wince the question requires not defacing the code, and that answer defaces :-) – ChrisJJ Sep 20 '15 at 23:17
  • "If $e is not an object" Thanks, but I have improved the example to show how this does not apply. – ChrisJJ Sep 20 '15 at 23:22
  • ChrisJJ, you wouldn't be getting that warning if it was an object. Do a `var_dump(file_get_html("http://google.com")->find['body'])` and post it as an update to your Q. – Devon Bessemer Sep 20 '15 at 23:46
  • Will do. And oops, my find[] should be find() of course. – ChrisJJ Sep 22 '15 at 00:10
0
file_get_html("http://google.com")->find('body',0)->bgcolor = '&675432';

find() was returning an array. Whilst I cannot see how this is an 'empty value' as per the error message, with ",0" added, find() returns an element, as is required by "->".

ChrisJJ
  • 2,191
  • 1
  • 25
  • 38