I would like to write a PHP script to extract all elements (and only ticker symbols) from the following external page: https://www.predictit.org/api/marketdata/all/
So at the time of this writing, the output would be
VAGOV17
DEM.VAGOV17
GOP.VAGOV17
NJGOV17
...
I've tried variations of loadXML() and DOMDocument::getElementsByTagName() but kept getting errors. The XML in the page above appears to be well formed.
Thanks in advance!
You could use SimpleXML to load a remote url .
Then you can use a foreach to loop through all of the data.
Example:
$context = stream_context_create(array('http' => array('header' => 'Accept: application/xml')));
$url = 'https://www.predictit.org/api/marketdata/all/';
$xml = file_get_contents($url, false, $context);
$elements = simplexml_load_string($xml);
foreach ($elements->Markets->MarketData as $marketData) {
echo $marketData->TickerSymbol . "<br>";
foreach ($marketData->Contracts->MarketContract as $contract) {
echo "-" . $contract->TickerSymbol . "<br>";
}
}
Will result in:
VAGOV17
-DEM.VAGOV17
-GOP.VAGOV17
NJGOV17
-DEM.NJGOV17
-GOP.NJGOV17
MAYOR.NYC2017
-BDB.MAYOR.NYC2017
-WEINER.MAYOR.NYC2017
-QUINN.MAYOR.NYC2017
-STRINGER.MAYOR.NYC2017
Etc..
Here is your Code. Let me know working or not
Hoping your xml file called 'all.xml'
<?php
if (file_exists('all.xml'))
{
$xml = simplexml_load_file('all.xml');
foreach ($xml as $k)
{
$tag = $k->getName();
$i = 0;
foreach($xml->$tag->children() as $key)
{
$marketData = $key->getName();
echo $xml->$tag->MarketData[$i++]->TickerSymbol . "<br>";
}
}
}
else
{
exit('Failed to open all.xml.');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.