Reputation: 601
I am trying to parse the symbols from the JSON below:
$trending_url = "https://api.stocktwits.com/api/2/trending/symbols/equities.json";
Example response here:
{
"response": {
"status": 200
},
"symbols": [{
"id": 11631,
"symbol": "JNUG",
"title": "Direxion Daily Jr Gld Mnrs Bull 3X Shrs",
"is_following": false
}, {
"id": 9553,
"symbol": "NUGT",
"title": "Direxion Daily Gold Miners Bull 3X Shrs",
"is_following": false
}, {
"id": 12100,
"symbol": "BABA",
"title": "Alibaba",
"is_following": false
}]
}
From above JSON-- i would like to extract the symbol's (i.e. JNUG, NUGT, BABA) through a loop. Here's what i did...
$trending_url_info = json_decode(file_get_contents($trending_url),true);
echo $trending_url_info->symbols->symbol[0] . "<br>";
echo $trending_url_info->response->symbols->symbol[0] . "<br>";
echo $trending_url_info->response->symbols[0]->symbol[0] . "<br>";
echo $trending_url_info['response']['symbols'][0]['symbol'] . "<br>";
echo $trending_url_info['response']['symbols'][0]['symbol'][0] . "<br>";
echo $trending_url_info['response']['symbols']['symbol'][0] . "<br>";
However none of the echo's above give me the symbol. How do i have a loop and extract the symbol's from the JSON feed? Any help is appreacited.. thanks.
Upvotes: 0
Views: 56
Reputation: 801
$trending_url = {
"response": {
"status": 200
},
"symbols": [{
"id": 11631,
"symbol": "JNUG",
"title": "Direxion Daily Jr Gld Mnrs Bull 3X Shrs",
"is_following": false
}, {
"id": 9553,
"symbol": "NUGT",
"title": "Direxion Daily Gold Miners Bull 3X Shrs",
"is_following": false
}, {
"id": 12100,
"symbol": "BABA",
"title": "Alibaba",
"is_following": false
}]
}
foreach($trending_url->symbols as $obj){
echo $obj->symbol."<br>";
}
Upvotes: 0
Reputation: 8870
symbols
is not under response
. That is why $trending_url_info['response']...
none of these are working. Also json_decode
with true
gives you associate array not an object.
$trending_url_info['symbols'][0]['symbol']
this should work.
$trending_url_info = json_decode(file_get_contents($trending_url),true);
$symbols = array();
foreach($trending_url_info['symbols'] as $sym) {
$symbols[] = $sym['symbol'];
}
echo(json_encode($symbols));
$symbols
will give [JNUG, NUGT, BABA]
Upvotes: 2
Reputation: 42984
This is a simple demonstration of the correct access to those properties:
<?php
$jsonInput = <<<EOT
{
"response": {
"status": 200
},
"symbols": [{
"id": 11631,
"symbol": "JNUG",
"title": "Direxion Daily Jr Gld Mnrs Bull 3X Shrs",
"is_following": false
}, {
"id": 9553,
"symbol": "NUGT",
"title": "Direxion Daily Gold Miners Bull 3X Shrs",
"is_following": false
}, {
"id": 12100,
"symbol": "BABA",
"title": "Alibaba",
"is_following": false
}]
}
EOT;
$jsonData = json_decode($jsonInput);
foreach ($jsonData->symbols as $symbol) {
var_dump($symbol->symbol);
}
The output obviously is:
string(4) "JNUG"
string(4) "NUGT"
string(4) "BABA"
Upvotes: 1