在使用 xpath 从 php 文件中提取数据之后。
我的代码:
$xml = simplexml_load_file("CCV.xml");
foreach ($xml->xpath('./section[@label="Education"]/section[@label="Degrees"]') as $details) {
foreach ($details->field as $f) {
$a = $f->attributes();
if ('Degree Type'== $a['label']){
$x = $f->lov;
var_dump($x);
break;
}
}
}
结果如下所示
object(SimpleXMLElement)[10]
public '@attributes' =>
array (size=1)
'id' => string '00000000000000000000000000000073' (length=32)
public 0 => string 'Doctorate' (length=9)
object(SimpleXMLElement)[9]
public '@attributes' =>
array (size=1)
'id' => string '00000000000000000000000000000072' (length=32)
public 0 => string 'Master's Thesis' (length=15)
object(SimpleXMLElement)[8]
public '@attributes' =>
array (size=1)
'id' => string '00000000000000000000000000000084' (length=32)
public 0 => string 'Bachelor's Equivalent' (length=21)
我怎么能只返回第一个带有博士学位的对象。
在 xpath 中,您可以将初始查询包装在 ()[1]
中,以获得另一个仅返回第一个匹配项的 xpath 查询:
(xpath/query/that/may/return/multiple/result)[1]
对于这种特殊情况,它应该是这样的:
(./section[@label="Education"]/section[@label="Degrees"])[1]
看起来你会使用
$x->0
这行得通吗? 0 是您需要的项目的键。 请注意,使用单个字母变量并不总是最好的,尤其是在循环中。 这可能会导致一些不必要的混乱。
<?php
$xml = simplexml_load_file("CCV.xml");
foreach ($xml->xpath('./section[@label="Education"]/section[@label="Degrees"]') as $details)
{
foreach ($details->field as $detailField)
{
$attribute = $detailField->attributes();
if ('Degree Type' == $attribute['label'])
{
$data = $detailField->0;
var_dump($data);
break;
}
}
}