I have some XML that I want to read into a SimpleXMLElement, the element values are then used as strings by casting the elements to string. For each SimpleXMLELement I'd like to change the element string before returning it. Rather than repeating the manipulation everywhere an element is accessed I'd like to do this in one place.
My first thought was to override SimpleXMLElement__toString but this seems to be only called with print and not by casting to string with (string).
Is there something else I should be overriding or is there a better approach to this?
<?php
$string_xml = "<?xml version='1.0' encoding='UTF-8'?>
<foo>
<bar>baz</bar>
</foo>";
$xml = simplexml_load_string($string_xml, 'ToStringTest');
print "cast ";
$s = (string)$xml->bar;
print $s;
// "cast baz" is printed
print "\nprint ";
print $xml->bar;
// "print uses __toStringbazfoo" is printed
class ToStringTest extends SimpleXMLElement
{
public function __toString()
{
print "uses __toString";
return parent::__toString() . 'foo';
}
}