使用PHP获取特定的XML元素值

使用PHP获取特定的XML元素值,php,xml,dom,Php,Xml,Dom,我有一个这样的XML结构 <companies> <company> <vatno>12345678</vatno> <name> <founded>2013-12-31</founded> <text>XYZ Inc</text> </name> <location>

我有一个这样的XML结构

<companies>
   <company>
      <vatno>12345678</vatno>
      <name>
         <founded>2013-12-31</founded>
         <text>XYZ Inc</text>
      </name>
      <location>
         <streetname>West Road</streetname>
         <county>
            <no>12345</no>
            <text>East County</text>
         <county>
      </location>
   </company>
</companies>
但是如果我需要县名的话呢


我不能使用getElementsByTagName('text'),因为它也会使用元素名“text”来获取公司名称。

您最好使用SimpleXML,然后可以以更直观的方式访问各种组件。 上面的例子类似于

$data = <<< XML
<companies>
   <company>
      <vatno>12345678</vatno>
      <name>
         <founded>2013-12-31</founded>
         <text>XYZ Inc</text>
      </name>
      <location>
         <streetname>West Road</streetname>
         <county>
            <no>12345</no>
            <text>East County</text>
         </county>
      </location>
   </company>
</companies>
XML;

$xml = simplexml_load_string($data);
foreach ( $xml->company as $company )   {
    echo $company->vatno.PHP_EOL;
    echo $company->location->county->text.PHP_EOL;
}

使用
项(1)
将获取
元素的第二个实例,因此这假设名称也将具有此值。

如果使用

$xml = simplexml_load_string($data);
foreach ( $xml->companies->company as $company )   {
    echo $company->vatno.PHP_EOL;
    echo $company->location->county->text.PHP_EOL;
}
$countyName = $xmlObject->item($i)->getElementsByTagName('text')->item(1)
->nodeValue;
$xml = simplexml_load_string($data);
foreach ( $xml->companies->company as $company )   {
    echo $company->vatno.PHP_EOL;
    echo $company->location->county->text.PHP_EOL;
}