首页 文章

如何使用xpath php获取元素xml

提问于
浏览
0

我有如何使用xpath php获取元素xml的问题,我已经创建了一个php文件,通过使用xpath php提取“属性”xml .

我想要的是如何使用xpath提取xml中的每个元素 .

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<InvoicingData>
 <CreationDate> 2014-02-02 </CreationDate>
 <OrderNumber> XXXX123 </OrderNumber>
 <InvoiceDetails>
   <InvoiceDetail>
   <SalesCode> XX1A </SalesCode>
   <SalesName> JohnDoe </SalesName>
</InvoiceDetail>
</InvoiceDetails>
</InvoicingData>

read.php

<?php
$doc = new DOMDocument();
$doc->loadXML(file_get_contents("test.xml"));
$xpath = new DOMXpath($doc);
$nodes = $xpath->query('//*');
$names = array();
foreach ($nodes as $node)
{
    $names[] = $node->nodeName;
}
echo join(PHP_EOL, ($names));
?>

从上面的代码,它将打印如下:

CreationDate OrderNumber InvoiceDetails InvoiceDetail SalesCode SalesName

所以,问题是,如何在属性中获取元素 basically this is what i want to print

2014-02-02 XXXX123 XX1A JohnDoe

1 回答

  • 1

    使用$node->textContent获取节点的文本值(及其后代,如果有的话) .


    回应您的第一条评论:

    你没有使用 $node->textContent . 试试这个:

    $doc = new DOMDocument();
    $doc->loadXML(file_get_contents("test.xml"));
    $xpath = new DOMXpath($doc);
    $nodes = $xpath->query('//*');
    $names = array();
    $values = array(); // created a separate array for the values
    foreach ($nodes as $node)
    {
      $names[]  = $node->nodeName;
      $values[] = $node->textContent; // push to $values array
    }
    echo join(PHP_EOL, ($values));
    

    但是,如果您只想在文本值成为元素的直接子元素时仍然想要收集所有节点名称,那么您可以执行以下操作:

    foreach ($nodes as $node)
    {
      $names[] = $node->nodeName;
      // check that this node only contains one text node
      if( $node->childNodes->length == 1 && $node->firstChild instanceof DOMText ) {
        $values[] = $node->textContent;
      }
    }
    echo join(PHP_EOL, ($values));
    

    如果您只关心直接包含文本值的节点,您可以执行以下操作:

    // this XPath query only selects those nodes that directly contain non-whitespace text
    $nodes = $xpath->query('//*[./text()[normalize-space()]]');
    $values = array();
    foreach ($nodes as $node)
    {
      // add nodeName as key
      // (only works reliable of there's never a duplicate nodeName in your XML)
      // and add textContent as value
      $values[ $node->nodeName ] = trim( $node->textContent );
    }
    
    var_dump( $values );
    

相关问题