简体   繁体   English

如何使用php解析xml以选择子节点?

[英]How to parse xml with php to select child node?

How can I select InsCode child node in this XML with PHP? 如何使用PHP在此XML中选择InsCode子节点?

I use simplexml_load_string but I can't select a child node! 我使用simplexml_load_string但无法选择子节点!

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<InstTradeResponse xmlns="http://tsetmc.com/">
<InstTradeResult>
<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="TradeSelectedDate">...</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<TradeSelectedDate xmlns="">
<TradeSelectedDate diffgr:id="TradeSelectedDate1" msdata:rowOrder="0">
<InsCode>70270965300262393</InsCode>
<DEven>20160507</DEven>
<HEven>123452</HEven>
<PClosing>1303.00</PClosing>
<IClose>0</IClose>
<YClose>3</YClose>
<PDrCotVal>1297.00</PDrCotVal>
<ZTotTran>222</ZTotTran>
<QTotTran5J>1966165</QTotTran5J>
<QTotCap>2561539385.00</QTotCap>
<PriceChange>-35.00</PriceChange>
<PriceMin>1270.00</PriceMin>
<PriceMax>1355.00</PriceMax>
<PriceYesterday>1332.00</PriceYesterday>
</TradeSelectedDate>
<TradeSelectedDate diffgr:id="TradeSelectedDate2" msdata:rowOrder="1">
<InsCode>70270965300262393</InsCode>
<DEven>20160508</DEven>
<HEven>122959</HEven>
<PClosing>1287.00</PClosing>
<IClose>0</IClose>
<YClose>3</YClose>
<PDrCotVal>1309.00</PDrCotVal>
<ZTotTran>281</ZTotTran>
<QTotTran5J>2600251</QTotTran5J>
<QTotCap>3347398897.00</QTotCap>
<PriceChange>6.00</PriceChange>
<PriceMin>1244.00</PriceMin>
<PriceMax>1310.00</PriceMax>
<PriceYesterday>1303.00</PriceYesterday>
</TradeSelectedDate>
</TradeSelectedDate>
</diffgr:diffgram>
</InstTradeResult>
</InstTradeResponse>
</soap:Body>
</soap:Envelope>

I try this code: 我尝试以下代码:

print_r ($data->InstTradeResult);
$xml  = $data->InstTradeResult->any;
//print_r($xml);
$sxml = simplexml_load_string( $xml );
$json = json_decode( json_encode( $sxml->xpath) );

If there is only one <InsCode> element, then you can just use XPath. 如果只有一个<InsCode>元素,则可以只使用XPath。 As this returns an array of matches, you just take the first element (using [0] ) and convert the value to a string... 当这返回一个匹配数组时,您只需获取第一个元素(使用[0] )并将值转换为字符串...

$sxml = simplexml_load_string( $xml );
$body = $sxml->xpath("//InsCode");
echo (string)$body[0];

Which with the sample XML you have gives... 您所提供的带有示例XML的哪个...

70270965300262393

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM