簡體   English   中英

如何使用php解析xml以選擇子節點?

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

如何使用PHP在此XML中選擇InsCode子節點?

我使用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>

我嘗試以下代碼:

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

如果只有一個<InsCode>元素,則可以只使用XPath。 當這返回一個匹配數組時,您只需獲取第一個元素(使用[0] )並將值轉換為字符串...

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

您所提供的帶有示例XML的哪個...

70270965300262393

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM