-
-
Save Albus/566fa960102e0a194f7460147047f33b to your computer and use it in GitHub Desktop.
PHP: convert XML to XPath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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