2

I am thinking of passing a XML string to a function then I'll return the parent node together with its value.

Say for an example:

$xml = "<Student><Name>Jee Pee</Name><Age>16</Age></Student>";
runXmltoStr($xml);

function runXmltoStr($xml)
{
// This is where I can't figure out where to start
// In my mind, I do have this output
//
// Student
// Name: Jee Pee
// Age: 16
}
1

3 Answers 3

6

You should use an XML parser, such as SimpleXML:

$xml_node = simplexml_load_string($xml);
$xml_node->Name; // Jee Pee
$xml_node->Age; // 16
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Tim Cooper. I tried to print_r($xml_node); but I don't see the Student on the key of an array. My purpose of looking for it is, I like to include it on my output.
@Dee: Like I posted, you can access the nodes like you would access an object's properties, like so: $simplexml_node->SubnodeName.
1

Use

simplexml_load_string($xml);

To load the string into an XML element and then use SimpleXML: http://php.net/manual/en/book.simplexml.php to get the elements.

Comments

0

Maybe you could give a look to the DOM manipulation features of PHP that can do all that kind of stuff for you.

DOM is not the fastest way of parsing XML but it's reliable and easy to implement over complex XML data structures.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.