0
votes

hello Everyone i have a strange question (for me its strange). i have an xml file like below:

<?xml version="1.0" encoding="ISO-8859-1"?>
<StudentsList>
<Student>
<student_id email="[email protected]">18700</student_id>
<firstName>Jhon</firstName>
<lastName>Smith</lastName>
<address>Dragon Vally china</address>
</Student>
<Student>
<student_id email="[email protected]">18701</student_id>
<firstName>Lee</firstName>
<lastName>Sin</lastName>
<address>League Of Legend UK</address>
</Student>
</StudentsList>

when i search that file using xpath in php like

$allStudents = $xml->xpath("//StudentsList/Student");

it give me all the students in an array with their child node and values like below:

Array ( [0] => SimpleXMLElement Object ( [student_id] => 18700 [firstName] => Jhon [lastName] => Smith [address] => Dragon Vally china ) [1] => SimpleXMLElement Object ( [student_id] => 18701 [firstName] => Lee [lastName] => Sin [address] => League Of Legend UK ) [2] => SimpleXMLElement Object ( [student_id] => 18702 [firstName] => Xin [lastName] => Xaho [address] => Shanghi China ) [3] => SimpleXMLElement Object ( [student_id] => 18703 [firstName] => corki [lastName] => adc [address] => flying machine gun china ) [4] => SimpleXMLElement Object ( [student_id] => 18704 [firstName] => Kog [lastName] => Maw [address] => Depth of The Hell ) )

but as i have an attribute to student_id node i also want to get the value of that attribute too can any one please suggest what to do for that i google a lot but didn't find right answer. they gave examples for selecting parent by its attribute value but atleast i didn't find the one who select it with the whole node of student.

1

1 Answers

1
votes

You can access an attribute named foo as $element['foo'], e.g.

$xml = <<<XML
    <StudentsList>
<Student>
<student_id email="[email protected]">18700</student_id>
<firstName>Jhon</firstName>
<lastName>Smith</lastName>
<address>Dragon Vally china</address>
</Student>
<Student>
<student_id email="[email protected]">18701</student_id>
<firstName>Lee</firstName>
<lastName>Sin</lastName>
<address>League Of Legend UK</address>
</Student>
</StudentsList>
XML;

$doc = new SimpleXMLElement($xml);

foreach ($doc->Student as $student) {
    echo $student->student_id['email'] . "\n";
}

outputs the two email addresses and of course with XPath the code is the same:

$xml = <<<XML
    <StudentsList>
<Student>
<student_id email="[email protected]">18700</student_id>
<firstName>Jhon</firstName>
<lastName>Smith</lastName>
<address>Dragon Vally china</address>
</Student>
<Student>
<student_id email="[email protected]">18701</student_id>
<firstName>Lee</firstName>
<lastName>Sin</lastName>
<address>League Of Legend UK</address>
</Student>
</StudentsList>
XML;

$doc = new SimpleXMLElement($xml);


foreach ($doc->xpath("//StudentsList/Student") as $student) {
    echo $student->student_id['email'] . "\n";
}