homepage Welcome to WebmasterWorld Guest from 54.205.247.203
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
simplexml - show path to element
breham




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

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

 

enigma1




msg:4217187
 2:46 pm on Oct 15, 2010 (gmt 0)

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;

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved