Skip to content

Instantly share code, notes, and snippets.

@hakre
Last active December 13, 2015 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakre/4959346 to your computer and use it in GitHub Desktop.
Save hakre/4959346 to your computer and use it in GitHub Desktop.
PHP function in XML?
<?php
/**
* PHP function in XML?
* @link http://stackoverflow.com/q/14888921/367456
* @link https://gist.github.com/hakre/4959346
* @link http://eval.in/9908
* @author hakre <hakre.wordpress.com>
*/
$xml = <<<BUFFER
<doThis><?php
function doThis()
{
return 'bang bang bang!';
}
?></doThis>
BUFFER;
/**
* XML PHP Processing Instruction Parser
*
* Generate Object based on PHP processing instructions.
*/
class PiDOMDocument extends DOMDocument
{
public function getObject($class = null)
{
$class || $class = uniqid(__CLASS__);
$xp = new DOMXPath($this);
$buffer = '';
foreach ($xp->query('processing-instruction("php")') as $pi) {
$buffer .= "\n" . $pi->data;
}
eval(sprintf("class %s {\n%s\n}", $class, $buffer));
return new $class;
}
}
echo "PiDOMDocument:\n==============\n";
$doc = new PiDOMDocument();
$doc->loadXML($xml);
$obj = $doc->getObject();
echo $obj->doThis();
echo "\n\nPiSimpleXMLElement:\n===================\n";
/**
* SimpleXMLElement integration of PiDOMDocument
*/
class PiSimpleXMLElement extends SimpleXMLElement
{
public function __call($name, $args) {
$doc = new PiDOMDocument();
$doc->loadXML($this->asXML());
$callback = array($doc->getObject(), $name);
return call_user_func_array($callback, $args);
}
}
$foo = simplexml_load_string($xml, 'PiSimpleXMLElement');
echo $foo->doThis(); //bang bang bang!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment