Solved

Parse XML using PHP printing both the values of attributes of each node & path info

Posted on 2013-12-11
10
468 Views
Last Modified: 2013-12-12
Hi

I've been asked to Parse XML using PHP printing both the values of attributes of each node & path info so wondered if any of you gurus could assist.

My colleague doesnt know what fields he finally wants mapped until he sees all the results so I thought it would be a good idea to pass the XML file and then he could pick and choose.

To then aid me in providing what he wants it would be good to get the path beside each output, so I'm looking for something like this: NOTE: this is not the XML I'll be using, he doesnt have that yet so the solution needs to be very generic and look after whatever is chucked at it.


The XML can and will go to many child levels, values and atributes etc.


<songs>
    <song dateplayed="2011-07-24 19:40:26">
        <title>I left my heart on Europa</title>
        <artist>Ship of Nomads</artist>
    </song>
    <song dateplayed="2011-07-24 19:27:42">
        <title>Oh Ganymede</title>
        <artist>Beefachanga</artist>
    </song>
    <song dateplayed="2011-07-24 19:23:50">
        <title>Kallichore</title>
        <artist>Jewitt K. Sheppard</artist>
    </song>
</songs>

Open in new window


So with this basically iterate the whole thing and produce something like:

2011-07-24 19:40:26 | song[0]['dateplayed']
I left my heart on Europa | song[0]->title
Ship of Nomads | song[0]->artist
2011-07-24 19:27:42 | song[1]['dateplayed']
Oh Ganymede | song[1]->title
Beefachanga | song[1]->artist
2011-07-24 19:23:50 | song[2]['dateplayed']
Kallichore | song[2]->title
Jewitt K. Sheppard | song[2]->artist

Regards
Neil
0
Comment
Question by:NeilT
  • 6
  • 4
10 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39713906
Sounds pretty theoretical, but the basic concept is "use the SimpleXML class."
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39713922
See if this makes sense.   I don't readily know how to determine the array key number, and I've never written any code that had a dependency on that.  But this shows how to get the attributes and data elements from the objects.
http://www.laprbass.com/RAY_temp_neilt.php

<?php // RAY_temp_neilt.php
error_reporting(E_ALL);
echo '<pre>';


// DEMONSTRATE HOW TO PARSE XML
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28316178.html


// TEST DATA FROM THE POST AT EE
$xml = <<<EOD
<songs>
    <song dateplayed="2011-07-24 19:40:26">
        <title>I left my heart on Europa</title>
        <artist>Ship of Nomads</artist>
    </song>
    <song dateplayed="2011-07-24 19:27:42">
        <title>Oh Ganymede</title>
        <artist>Beefachanga</artist>
    </song>
    <song dateplayed="2011-07-24 19:23:50">
        <title>Kallichore</title>
        <artist>Jewitt K. Sheppard</artist>
    </song>
</songs>
EOD;


// MAKE AN OBJECT
$obj = SimpleXML_Load_String($xml);

// ACTIVATE THIS TO SEE THE OBJECT
// var_dump($obj);

// USE AN ITERATOR TO ACCESS THE INFORMATION
foreach ($obj as $song)
{
    $d = $song['dateplayed'];
    $t = $song->title;
    $a = $song->artist;
    echo PHP_EOL . "ON $d WE PLAYED SONG $t BY ARTIST $a";
}

Open in new window

HTH, ~Ray
0
 
LVL 3

Author Comment

by:NeilT
ID: 39713945
Thanks Ray,

The unfortunate thing is in the real life XML we do not yet know the node names or attributes so I'm looking for something that can scan the entire tree, giving back not only the values but also its own array path to that attribute or node value.

does that make sense?

Neil
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39713956
No, it sounds so theoretical as to be an unusable concept.  What would the data source be that had unknowable node names?
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39713979
This is agnostic about node names.  I don't have an example for recursive traversal.   You might want to look into the SPL.  There may be something in the iterators.

<?php // RAY_temp_neilt.php
error_reporting(E_ALL);
echo '<pre>';


// DEMONSTRATE HOW TO PARSE XML
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28316178.html


// TEST DATA FROM THE POST AT EE
$xml = <<<EOD
<songs>
    <song dateplayed="2011-07-24 19:40:26">
        <title>I left my heart on Europa</title>
        <artist>Ship of Nomads</artist>
    </song>
    <song dateplayed="2011-07-24 19:27:42">
        <title>Oh Ganymede</title>
        <artist>Beefachanga</artist>
    </song>
    <song dateplayed="2011-07-24 19:23:50">
        <title>Kallichore</title>
        <artist>Jewitt K. Sheppard</artist>
    </song>
</songs>
EOD;


// MAKE AN OBJECT
$obj = SimpleXML_Load_String($xml);

// ACTIVATE THIS TO SEE THE OBJECT
var_dump($obj);

// USE AN ITERATOR TO ACCESS THE INFORMATION
foreach ($obj as $thing)
{
    foreach ($thing->attributes() as $akey => $attr)
    {
        echo PHP_EOL . "$akey -> $attr";
    }
    foreach ($thing as $key => $data)
    {
        echo PHP_EOL . "$key -> $data";
    }
    echo PHP_EOL;
}

Open in new window

0
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 3

Author Comment

by:NeilT
ID: 39714008
Thanks Ray ill take a look. Sorry to be so vague on this it's just we don't have the XML files as yet as they are being sorted by a third party. When we get them I need to have them all on a website in a day but only the bits someone here wants, not it all

Aaagh!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39714183
need to have them all on a website in a day
And I want to be able to run a marathon in under two hours!  Some goals are unreasonable, and I think good judgement about realistic timelines is one of the important parts of business management.  It is unreasonable to say, in effect, "You cannot have any test data and you must use whatever we give you to achieve a result in a day."  No amount of preparation will predictably lead to success.  What if the XML document is malformed?  These are the things you need to find out beforehand, so you can mock up the XML and write the programming.

Best of luck with it, and I hope you're getting paid a lot of money!! ~Ray
0
 
LVL 3

Author Comment

by:NeilT
ID: 39715143
Thanks Ray, I'll take a look what I can do with SimpleXML and some sort of iteration.

perils of UK local authorities unfortunately, everything is always last minute, zero budget required yesterday and your fault when it's not done.

One of the reasons I have no hair :)
0
 
LVL 3

Author Closing Comment

by:NeilT
ID: 39715159
Superb thank you, neil
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39715494
... the reasons I have no hair :)
You must be going to my barber!  Thanks for the points and thanks for using EE, ~Ray
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now