在PHP中解析DOMNodeList

时间:2011-01-21 12:04:46

标签: php xml parsing

Web服务返回格式为

的Xml
<string>
  <NewDataSet>
    <DealBlotter>
      <CustomerReference>161403239</CustomerReference>
      <Symbol>EUR/USD</Symbol>
      <BuySell>S</BuySell>
      <ContractValue>-100000</ContractValue>
      <Price>1.35070</Price>
      <CounterValue>-135070</CounterValue>
      <TradeDate>2011-01-20 22:05:21.690</TradeDate>
      <ConfirmationNumber>78967117</ConfirmationNumber>
      <Status>C</Status>
      <lTID>111913820</lTID>
    </DealBlotter>
  </NewDataSet>
</string>

现在我使用curl访问它然后 -

$xml = simplexml_load_string($result);
$dom = new DOMDOcument();

// Load your XML as a string
$dom->loadXML($xml);

// Create new XPath object
$xpath = new DOMXpath($dom);

$res = $xpath->query("/NewDataSet/DealBlotter");

foreach($res as $node)
{
    print "i went inside foreach";
    $custref =  ($node->getElementsByTagName("CustomerReference")->item(0)->nodeValue);
    print $custref;
    $ccy = ($node->getElementsByTagName("Symbol")->item(0)->nodeValue);
    print $ccy;
    $type = ($node->getElementsByTagName("BuySell")->item(0)->nodeValue);
    $lots = ($node->getElementsByTagName("ContractValue")->item(0)->nodeValue);
    $price = ($node->getElementsByTagName("Price")->item(0)->nodeValue);
    $confnumber = ($node->getElementsByTagName("ConfirmationNumber")->item(0)->nodeValue);
    $status = ($node->getElementsByTagName("Status")->item(0)->nodeValue);
    $ltid = ($node->getElementsByTagName("lTID")->item(0)->nodeValue);
    $time = ($node->getElementsByTagName("TradeDate")->item(0)->nodeValue);

}

但没有任何内容可以打印。除了虚拟声明。 使用$res = $xpath->query("/string/NewDataSet/DealBlotter");没有帮助。另外,print_r($res);会将输出设为DOMNodeList obect.

这样做也不会打印任何内容

$objDOM = new DOMDocument(); 
$objDOM->load($result);
$note = $objDOM->getElementsByTagName("DealBlotter");
foreach( $note as $value )
{       
    print "hello";  
    $tasks = $value->getElementsByTagName("Symbol");
    $task  = (string)$tasks->item(0)->nodeValue;

    $details = $value->getElementsByTagName("Status");
    $detail  = (string)$details->item(0)->nodeValue;

    print "$task :: $detail <br>"; 
}

1 个答案:

答案 0 :(得分:0)

有一些问题。

了解如何加载xml。摆脱simplexml行。这不是必需的,而且搞砸了。而只是做$dom->loadXml($result);。如果您要将SimpleXML直接传递给DomDocument,则没有理由首先加载SimpleXML。

使用您的查询,/运算符是直接运算符。所以它意味着紧挨着。所以你的第一个标签应该是根。所以要么将root添加到它上面:

$res = $xpath->query("/string/NewDataSet/DealBlotter");

或者将前导斜杠设为//,选择任何匹配的后代:

$res = $xpath->query("//NewDataSet/DealBlotter");

最后,在var_dump上执行$res并不会告诉你太多。相反,我喜欢做var_dump($res->length)因为它会告诉你它有多少匹配,而不是它是一个domnodelist(你已经知道)...