Skip to content

Instantly share code, notes, and snippets.

@ThomasWeinert
Created August 24, 2015 11:51
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 ThomasWeinert/71ba036c6afa863a9346 to your computer and use it in GitHub Desktop.
Save ThomasWeinert/71ba036c6afa863a9346 to your computer and use it in GitHub Desktop.
Using a callback to fetch the current context in an xpath expression, this might allow to implement the CSS selector `:scope`
<?php
$xml = file_get_contents('php://stdin');
class MyXpath extends DOMXpath {
private static $_context = null;
public function __construct($document) {
parent::__construct($document);
$this->registerNamespace("php", "http://php.net/xpath");
$this->registerPHPFunctions([self::CLASS.'::getContext']);
}
public function evaluate($expression, $context = NULL, $registerNamespaces = FALSE) {
self::$_context = $context;
return parent::evaluate($expression, $context, $registerNamespaces);
}
public function getContext() {
return self::$_context;
}
}
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new MyXpath($document);
$xpath->registerPhpFunctions(['getContext']);
foreach ($xpath->evaluate('//item') as $item) {
var_dump($xpath->evaluate('name(//*/.)', $item));
var_dump($xpath->evaluate('name(//*[. = php:function("MyXpath::getContext")])', $item));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment