Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created August 31, 2013 09:00
Show Gist options
  • Save hubgit/6397048 to your computer and use it in GitHub Desktop.
Save hubgit/6397048 to your computer and use it in GitHub Desktop.
Add XPath methods to DOMDocument
<?php
class QueryDOMDocument extends \DOMDocument
{
/** @var \DOMXPath */
protected $xpath;
public function __construct()
{
parent::__construct();
$this->registerNodeClass('DOMNode', 'QueryDOMNode');
$this->registerNodeClass('DOMElement', 'QueryDOMElement');
}
public function load($file, $options = null)
{
parent::load($file, $options);
$this->xpath = new DOMXPath($this);
}
public function registerNamespace($prefix, $namespaceURI)
{
$this->xpath->registerNamespace($prefix, $namespaceURI);
}
public function registerPhpFunctions($restrict)
{
$this->xpath->registerPhpFunctions($restrict);
}
public function query($xpath, $contextNode = null)
{
return $this->xpath->query($xpath, $contextNode);
}
public function evaluate($xpath, $contextNode = null)
{
return $this->xpath->evaluate($xpath, $contextNode);
}
}
class QueryDOMElement extends \DOMElement
{
use DOMNodeXPath;
}
class QueryDOMNode extends \DOMNode
{
use DOMNodeXPath;
}
trait DOMNodeXPath
{
public function query($xpath)
{
return $this->ownerDocument->query($xpath, $this);
}
public function evaluate($xpath)
{
return $this->ownerDocument->evaluate($xpath, $this);
}
}
<?php
require 'QueryDOM.php';
$doc = new QueryDOMDocument();
$doc->load('test.xml');
$doc->registerNamespace('oai', 'http://www.openarchives.org/OAI/2.0/');
$doc->registerNamespace('oai_dc', 'http://www.openarchives.org/OAI/2.0/oai_dc/');
$doc->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
foreach ($doc->query('oai:ListRecords/oai:record/oai:metadata/oai_dc:dc') as $item) {
$data = array(
'date' => $item->evaluate('string(dc:date)'),
'source' => array(),
);
foreach ($item->query('dc:source') as $source) {
$data['source'][] = $source->textContent;
}
print_r($data);
}
<OAI-PMH
xmlns="http://www.openarchives.org/OAI/2.0/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dc="http://dublincore.org/documents/dcmi-namespace/"
xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd">
<responseDate>2013-04-15T12:14:31Z</responseDate>
<ListRecords>
<record>
<header>
<identifier>123</identifier>
<datestamp>2013-08-16T14:42:52Z</datestamp>
</header>
<metadata>
<oai_dc:dc
xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd">
<dc:date>2013-09-16</dc:date>
<dc:source>123</dc:source>
<dc:source>456</dc:source>
</oai_dc:dc>
</metadata>
<about></about>
</record>
</ListRecords>
</OAI-PMH>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment