如何使用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) );
答案 0 :(得分:1)
If there is only one <InsCode>
element, then you can just use XPath. As this returns an array of matches, you just take the first element (using [0]
) and convert the value to a string...
$sxml = simplexml_load_string( $xml );
$body = $sxml->xpath("//InsCode");
echo (string)$body[0];
Which with the sample XML you have gives...
70270965300262393