使用SimpleXMLElement仅显示第一个对象

时间:2015-04-24 22:46:01

标签: php xpath

使用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) 

如何仅使用博士返回第一个对象。

2 个答案:

答案 0 :(得分:1)

看起来你会用

#include <stdexcept>
long double rintl(long double arg) { throw std::runtime_error("rintl not implemented"); }
long lrintl(long double arg) { throw std::runtime_error("lrintl not implemented"); }

#include <cmath>

这有用吗? 0是您需要的项目的关键。请注意,使用单字母变量并不总是最好,特别是在循环中。这可能会引起一些不必要的混淆。

$x->0

答案 1 :(得分:1)

在xpath中,您可以在()[1]中包装初始查询,以获取另一个仅返回第一个匹配的xpath查询:

(xpath/query/that/may/return/multiple/result)[1]

对于这种特殊情况,它应该是这样的:

(./section[@label="Education"]/section[@label="Degrees"])[1]