Welcome to WebmasterWorld Guest from 54.163.100.58

Forum Moderators: coopster & jatar k

simplexml - show path to element

   
7:13 am on Oct 14, 2010 (gmt 0)

5+ Year Member



Hi, I have feed different XML files with different formats that I want to let users map to our database themselves. Example

<product>
<details>
<name>Product One</product>
<cost>20.00</cost>
<available>2</available>
</details>
<technical>
<width>3.00</width>
<height>2.10</height>
</technical>
</product>

What I need to do is be able to loop through the XML document and output the path for each element i.e.

name = "product>details->name"
cost = "product->details->cost"

Like I said there is a different and unknown format for each XML doc.

Any suggestions gratefully received. I have a process that can pull out the asset names i.e. width, height etc but not the path within the document.

Many thanks
Brett
2:46 pm on Oct 15, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



Are you using PHP? Here is couple of functions I did


function recxml_array($object=null, &$result_array=array()) {
if(is_object($object) ) {
$name = $object->getName();
if( !isset($result_array[$name]) ) {
$result_array[$name] = array();
}
foreach($object->children() as $element) {
recxml_array($element, $result_array[$name]);
}
}

}
function recxml_display($input_array, &$string = '') {
if( empty($input_array) || !is_array($input_array) ) {
echo $string . '<br />';
$string = '';
}

foreach($input_array as $key => $value ) {
$org_string = $string;
$string .= (!empty($string)?'&nbsp;&raquo;&nbsp;':'') . $key;
recxml_display($value, $string);
$string = $org_string;
}
}
$xml = new SimpleXMLElement($string);
recxml_array($xml, $result_array);
recxml_display($result_array);


The first function iterates through the xml object building up an md array that holds the xml elements as keys. The second function processes the php array to display the paths. It should work regardless of paths. Here is some XML for testing, just assign it to the $string var which is basically the input:


$string = <<<XML
<data>
<details>
<title>My Title</title>
<date>Jan 2009</date>
<fields>
<attr1>15</attr1>
<attr2>16</attr2>
</fields>
</details>
<item>An Item</item>
</data>
XML;
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month