|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-09-16 05:51 UTC] tatarynowicz at gmail dot com
Description:
------------
The problem is readily apparent when you run the test script. When
SimpleXMLElement dynamically creates a child element, and you directly call a
method on the child element, the $this context is apparently not a proper
SimpleXMLElement, i.e. dom_import_simplexml() does not accept it as input.
class MyXML extends SimpleXMLElement {
public function cdata($text) {
dom_import_simplexml($this);
}
}
$xml = new MyXML('<foo/>');
$xml->three->cdata('Three');
Test script:
---------------
<?php
class MyXML extends SimpleXMLElement {
public function cdata($text) {
$node = dom_import_simplexml($this);
$owner = $node->ownerDocument;
$node->appendChild($owner->createCDATASection($text));
return $this;
}
}
$xml = new MyXML('<foo/>');
// works
$xml->one = 'One';
// also works
$xml->two = '';
$xml->two->cdata('Two');
// doesn't work
$xml->three->cdata('Three');
print $xml->asXML();
Expected result:
----------------
<?xml version="1.0"?>
<foo><one>One</one><two><![CDATA[Two]]></two><three><![CDATA[Three]]></three></foo
>
Actual result:
--------------
Warning: dom_import_simplexml(): Invalid Nodetype to import in
C:\WWW\Work\WC\www\dom.php on line 5
Notice: Trying to get property of non-object in C:\WWW\Work\WC\www\dom.php on line
6
Fatal error: Call to a member function appendChild() on a non-object in
C:\WWW\Work\WC\www\dom.php on line 7
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 02:00:01 2025 UTC |
Please compare what you do with: $xml->three->addChild('alpha'); You will get a warning: Warning: SimpleXMLElement::addChild(): Cannot add child. Parent is not a permanent member of the XML tree If you extend from SompleXMLElement you probably want to add a similar warning for your function. You can check for the condition this way: if ($this[0] == NULL) { $where = __CLASS__ . '::' . __FUNCTION__ . '(): '; $what = 'Cannot add child. Parent is not a permanent member of the XML tree'; trigger_error($where . $what, E_USER_WARNING); return; } I hope this is helpful and makes the bigger picture more clear that this is how SimpleXMLElement works. You can however create your own type that does know how to add this on the fly, however due to the magic nature of SimpleXMLElement, it is not possible as long as you extend from SimpleXMLElement. It requires you to create a decorator and write code for that part of the magic your own and delegate the rest to the SimpleXMLElement decoratee / subject.