使用XML / Xpath / PHP获取元素名称/值

时间:2011-01-24 21:05:58

标签: php xml getelementsbytagname

我有一个XML架构,如下所示:

<xml>
  <user id="1">
    <first_name>Bill</first_name>
    <last_name>Steve</last_name>
    <phone_numbers>
      <work>xxx-xxx-xxxx</work>
      <home>xxx-xxx-xxxx</home>
    </phone_numbers>
   </user>
   <user id="2">
      ........
   </user>
</xml>

我正致力于使用DOM将所有这些信息解析为PHP。实施例

$userInfo = $doc->getElementsByTagName( "user" ); 
foreach($userInfo as $row)
{
       $first_name = $row->getElementsByTagName("first_name");
}

当我尝试嵌套此选择电话号码时,我收到错误。我尝试使用XPath来选择具有相同问题的电话号码。我尝试了一些

的方法
$userInfo = $doc->getElementsByTagName( "user" ); 
foreach($userInfo as $row)
{
       $phoneInfo = $row->getElementsByTagName("phone_numbers");
       foreach($phoneInfo as $row2)
       {
            $work = $row2->getElementsByTagName("work");
       }
}

我很好奇,如果我做了一些根本错误的事情,或者如何实现这一目标。我现在已经把头发撕了几个小时了。

2 个答案:

答案 0 :(得分:3)

您无法直接从DOMNodeList对象获取值,请尝试:

$userInfo = $doc->getElementsByTagName( "user" ); 
foreach($userInfo as $row)
{
       $phoneInfo = $row->getElementsByTagName("phone_numbers");
       foreach($phoneInfo as $row2)
       {
            // get the value from the first child
            $work = $row2->getElementsByTagName("work")->item(0)->nodeValue;
            $home = $row2->getElementsByTagName("home")->item(0)->nodeValue;
       }
}

答案 1 :(得分:1)

好吧,你可以将它切换到SimpleXml,这使得这种类型的解析更容易:

$userInfo = $doc->getElementsByTagName( "user" ); 
foreach ($userInfo as $user) {
    $node = simplexml_import_dom($user);
    $id = (string) $node['id'];
    $first = (string) $node->first_name;
    $last = (string) $node->last_name;
    $workPhone = (string) $node->phone_numbers->work;
    $homePhone = (string) $node->phone_numbers->home;
}

现在,在DomDocument中,您可以使用DomXpath

来完成此操作
$userInfo = $doc->getElementsByTagName( "user" ); 
$xpath = new DomXpath($doc);
foreach ($userInfo as $user) {
    $id = $user->getAttribute('id');
    $first = $xpath->query('//first_name', $user)->item(0)->textContent;
    $last = $xpath->query('//last_name', $user)->item(0)->textContent;
    $work = $xpath->query('//phone_numbers/work', $user)->item(0)->textContent;
    $home = $xpath->query('//phone_numbers/home', $user)->item(0)->textContent;
}

请注意,上面的代码(两个部分)都要求格式正是如此。如果您有条件,您可能希望将其更改为类似的内容(仅firstname条件):

$userInfo = $doc->getElementsByTagName( "user" ); 
$xpath = new DomXpath($doc);
foreach ($userInfo as $user) {
    $id = $user->getAttribute('id');
    $firstQuery = $xpath->query('//first_name', $user);
    if ($firstQuery->length > 0) {
        $first = $firstQuery->item(0)->textContent;
    } else {
        $first = '';
    }
}