Skip to content

Instantly share code, notes, and snippets.

@Divi
Last active August 6, 2017 08:43
Show Gist options
  • Save Divi/9003769 to your computer and use it in GitHub Desktop.
Save Divi/9003769 to your computer and use it in GitHub Desktop.
PHP: convert XML to XPath
<?php
// this function will show the full xpath of an XML file
// your code
$xml = new \SimpleXMLIterator('<root><node><foo bar="12">fooBar</foo><foo>bar</foo></node></root>');
$xpath = xmlToXPath($xml);
// the magic function
// from http://php.net/manual/fr/class.simplexmliterator.php#111916
function xmlToXPath($xml, $key = null, &$tmp = null)
{
$keys_arr = array();
// Get the keys count array
for ($xml->rewind(); $xml->valid(); $xml->next()) {
$sk = $xml->key();
if (array_key_exists($sk, $keys_arr)) {
$keys_arr[$sk]+=1;
$keys_arr[$sk] = $keys_arr[$sk];
}
else {
$keys_arr[$sk] = 1;
}
}
// Create the xpath
for ($xml->rewind(); $xml->valid(); $xml->next()) {
$sk = $xml->key();
if (!isset($$sk)) {
$$sk = 1;
}
if ($keys_arr[$sk] >= 1) {
$spk = $sk . '[' . $$sk . ']';
$keys_arr[$sk] = $keys_arr[$sk] - 1;
$$sk++;
}
else {
$spk = $sk;
}
$kp = $key ? $key . '/' . $spk : '/' . $xml->getName() . '/' . $spk;
if ($xml->hasChildren()) {
xmlToXPath($xml->getChildren(), $kp, $tmp);
}
else {
$tmp[$kp] = strval($xml->current());
}
$at = $xml->current()->attributes();
if ($at) {
$tmp_kp = $kp;
foreach ($at as $k => $v) {
$kp .= '/@' . $k;
$tmp[$kp] = $v;
$kp = $tmp_kp;
}
}
}
return $tmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment