3

我有一个如下所示的 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");
       }
}

我很好奇我是否做一些根本错误的事情,或者如何让这件事发生。我已经把头发扯了几个小时了。

4

2 回答 2

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;
       }
}
于 2011-01-24T21:30:44.710 回答
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 = '';
    }
}
于 2011-01-24T21:19:16.910 回答