Is it possible to write a PHP function in a XML
<doThis>
doThis(){
bang bang bang!
}
</doThis>
and use simplexml_load_file
to get the object with that function?
$foo = simplexml_load_file($xmlAbove);
$foo->doThis(); //bang bang bang!
Is it possible to write a PHP function in a XML
<doThis>
doThis(){
bang bang bang!
}
</doThis>
and use simplexml_load_file
to get the object with that function?
$foo = simplexml_load_file($xmlAbove);
$foo->doThis(); //bang bang bang!
XML has support for embedding so called Processing Instructions (PI), a valid XML could look like this:
which is pretty similar to what you know from the PHP language. However support only means, that you can put processing instructions in there but the processing of those instructions is not of the XML's business.
Also the XML parser you use - SimpleXML - has no dedicated support for processing instructions. You can use DOMDocument for that instead. So much from the XML side.
For the PHP side you have got the problem that you somehow define a function while you want to call it instead. Also the PHP code is invalid in other parts (probably because you just put together a quick question). Maybe this is better:
With some little DOM based parser (here called
PiDOMDocument
) this can be turned into a class/object:The output of
echo
in the last line then is:(quelle surprise). You could internally map this into a SimpleXMLElement to streamline that into your example code above:
This works like:
As PHP processor you can take
eval
orinclude
(which basically is both the same). PHP is executed directly so if your code has fatal parse errors, the overall script has fatal errors, if you do not like this PHP default behavior, you can parse the string before eval'ing it for such errors, see as welltoken_get_all()
and this example or this example.I opted for an unvalidated
eval
in my online demo / example code as gist.Firstly, you should always consider the security implications of running "code" like this. If this XML file has remote origins, and you execute the code, then it might do anything. What about
exec(rm -fR /some/important/path);
? Or a database call that deletes everything? There needs to be a very strong trust relationship between the sender and your code, and also strong security protocols to prevent man-in-the-middle and other attacks.To your question, it is not possible directly. As commented, XML is data, not code, and is supposed to be portable, meaning your PHP code will be nonsense to another client accepting this XML.
However, you could use
eval
. Maybe like this:Note: I wouldn't recommend this at all. It isn't the intended use of XML and it has many problems. Please, think of some other way.