Skip to content

Instantly share code, notes, and snippets.

@PeeHaa
Forked from gooh/xpath_match_all
Last active December 11, 2015 04:38
Show Gist options
  • Save PeeHaa/4546595 to your computer and use it in GitHub Desktop.
Save PeeHaa/4546595 to your computer and use it in GitHub Desktop.
<?php
function xpath_match_all($query, $html = '')
{
static $dom;
static $xpath;
static $content;
if (!$dom) {
$dom = new DOMDocument;
}
if ($html !== '') {
$content = $html;
$use_errors = libxml_use_internal_errors(true);
$dom->loadHtml($html);
$xpath = new DOMXPath($dom);
libxml_use_internal_errors($use_errors);
}
$matches = array(array(), array());
foreach ($xpath->query($query) as $i => $resultNode) {
$save = version_compare(PHP_VERSION, '5.3.6', '<') ? 'saveXml' : 'saveHtml';
$matches[0][] = $dom->$save($resultNode);
$innerHtml = '';
if ($resultNode->childNodes) {
foreach ($resultNode->childNodes as $childNode) {
$innerHtml .= $dom->$save($childNode);
}
}
$matches[1][] = $innerHtml;
}
return $matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment