I am trying to access a single data point from the XML below. My goal would then be to insert into an html table. The following code has been giving me a stdClass Object and I can’t figure out how to grab a single data point.
Here is the XML:
JavaScript
x
<?xml version="1.0" encoding="utf-8"?>
<response>
<status>
<code>0</code>
<message>OK</message>
</status>
<data _idtype="ticker" _id="QYLD" _MstarId="F00000QEMN" _CurrencyId="CU$$$$$USD">
<api _id="z87pq63qh3gbhraf">
<TS-DayEndTradingVolume>55769</TS-DayEndTradingVolume>
<TS-DayEndNAV>25.11</TS-DayEndNAV>
<DP-NAVChange>0.11</DP-NAVChange>
<DP-NAVChangePercentage>0.440000</DP-NAVChangePercentage>
<FNA-FundNetAssets>186075814</FNA-FundNetAssets>
<DP-DayEndDate>2018-02-27</DP-DayEndDate>
<TS-MarketPriceOpen>25.2</TS-MarketPriceOpen>
<PS-PriceToEarnings>0.03678</PS-PriceToEarnings>
<TS-DayEndMarketPrice>25.06</TS-DayEndMarketPrice>
<DMP-MarketPriceChange>-0.07</DMP-MarketPriceChange>
<DMP-MarketPriceChangePercentage>-0.278552</DMP-MarketPriceChangePercentage>
<DTTRV-NAV>24.98000</DTTRV-NAV>
<DMP-SharesOutstanding>7448991.76741</DMP-SharesOutstanding>
<DP-PremiumDiscount>0.32</DP-PremiumDiscount>
</api>
</data>
</response>
And the PHP:
JavaScript
$xml = simplexml_load_file($url); // URL with above XML
$jsonConvert = json_encode($xml);
$singleDataPoint = json_decode($jsonConvert);
print_r($singleDataPoint)
Advertisement
Answer
Actually your json functions are not doing anything at all. json_encode
is the opposite of json_decode
, so you can just completely omit those two lines.
The contents of the data points can be found, for example:
JavaScript
$xml = simplexml_load_file($url);
var_dump($xml->data->api->{'TS-DayEndTradingVolume'}->__tostring());
If you’re just echo
ing the value or using it in a string context, you don’t need __toString()
since that will be implied, but beware that without this, it is really an instance of an SimpleXMLElement
object, not an actual string.