你好每个人都有一个奇怪的问题(对我来说这很奇怪)。我有一个xml文件 如下所示:
<?xml version="1.0" encoding="ISO-8859-1"?>
<StudentsList>
<Student>
<student_id email="test@yahoo.com">18700</student_id>
<firstName>Jhon</firstName>
<lastName>Smith</lastName>
<address>Dragon Vally china</address>
</Student>
<Student>
<student_id email="LeeSin@gmail.com">18701</student_id>
<firstName>Lee</firstName>
<lastName>Sin</lastName>
<address>League Of Legend UK</address>
</Student>
</StudentsList>
当我在php中使用xpath搜索该文件时
$allStudents = $xml->xpath("//StudentsList/Student");
它为我的所有学生提供了他们的子节点和下面的值:
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 ) )
但由于我有一个student_id节点的属性我也想得到该属性的值也可以任何人请建议该怎么做我谷歌很多但没有找到正确的答案。他们提供了通过其属性值选择父级的示例,但至少我没有找到使用整个学生节点选择它的人。
答案 0 :(得分:1)
您可以将名为foo
的属性作为$element['foo']
访问,例如
$xml = <<<XML
<StudentsList>
<Student>
<student_id email="test@yahoo.com">18700</student_id>
<firstName>Jhon</firstName>
<lastName>Smith</lastName>
<address>Dragon Vally china</address>
</Student>
<Student>
<student_id email="LeeSin@gmail.com">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";
}
输出两个电子邮件地址,当然还有XPath,代码是相同的:
$xml = <<<XML
<StudentsList>
<Student>
<student_id email="test@yahoo.com">18700</student_id>
<firstName>Jhon</firstName>
<lastName>Smith</lastName>
<address>Dragon Vally china</address>
</Student>
<Student>
<student_id email="LeeSin@gmail.com">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";
}