3

If I delete an element inside an element, and if its the last element, then the parent element gets shortened to an empty element.

Example:

Start: <element><child1>Inner HTML</child1><child2>Inner HTML</child2></element>

I delete Child2 and I get: <element><child1>Inner HTML</child1></element>

I delete Child1 and I get: <element/>

Now I want that to not happen or at least a way to detect if the element is empty so I can replace it. How can I do that using DOMDocument in PHP.

Thanks...

3
  • What do you mean by "want that to not happen?" What do you want to have happen instead? What code are you using to delete the other elements? Commented Dec 29, 2011 at 14:47
  • Code should be definitely provided with this explanation. If you want to detect is element empty or not you could simply after deleting or before check php.net/manual/en/domnode.haschildnodes.php Commented Dec 29, 2011 at 14:49
  • actually, i found the error... it was due to something else. sorry for posting this question... Commented Dec 29, 2011 at 15:11

2 Answers 2

5

You should be able to determine whether an element is empty by inspecting the length of the list of child nodes:

$isEmpty = $elem->childNodes->length === 0;

Note that not only elements can be child nodes of another element but also CDATA sections, comments, and plain text.

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

1 Comment

actually, i found the error... it was due to something else. sorry for posting this question... but thanks for your answer...
3

Borrowing from the PHP manual:

count($elem->children());

So, to check if empty:

$isEmpty = count($elem->children()) === 0 ? true : false;

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.