I have php script which returns video streams as output. Output contains multiple unique streams.
I am trying to encode output into json but because of multiple foreach loop its not giving proper output
Code :
<?php
if (isset($_GET["id"]))
$id = $_GET["id"];
$temp = explode("=",$id);
$link=end($temp);
parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$link), $video_data);
$streams = $video_data['url_encoded_fmt_stream_map'];
$streams = explode(',',$streams);
$arr = array();
foreach ($streams as $streamdata) {
parse_str($streamdata,$streamdata);
foreach ($streamdata as $key => $value) {
$myObj->$key = $value;
}
$arr = $myObj;
}
echo json_encode(array("streams"=>$arr));
?>
Above code will return only last stream/item from output.
Output :
{
"streams":{
"quality":"small",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\"",
"itag":"17",
"url":"video_link"
}
}
If i put echo json_encode(array("streams"=>$arr)); inside upper foreach loop.
It will return all streams with multiple root nodes, and its not acceptable.
I need only one root node which contains all steams.
Output :
{
"streams":{
"type":"video\/mp4; codecs=\"avc1.64001F, mp4a.40.2\"",
"itag":"22",
"url":"video_link",
"quality":"hd720"
}
}{
"streams":{
"type":"video\/webm; codecs=\"vp8.0, vorbis\"",
"itag":"43",
"url":"video_link",
"quality":"medium"
}
}{
"streams":{
"type":"video\/mp4; codecs=\"avc1.42001E, mp4a.40.2\"",
"itag":"18",
"url":"video_link",
"quality":"medium"
}
}{
"streams":{
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\"",
"itag":"36",
"url":"video_link",
"quality":"small"
}
}{
"streams":{
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\"",
"itag":"17",
"url":"video_link",
"quality":"small"
}
}
Desired output will be :
{
"streams":[
{
"quality":"hd720",
"itag":"44",
"url":"video_link",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\""
},
{
"quality":"medium",
"itag":"",
"url":"video_link",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\""
},
{
"quality":"medium",
"itag":"17",
"url":"video_link",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\""
},
{
"quality":"medium",
"itag":"17",
"url":"video_link",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\""
},
{
"quality":"small",
"itag":"17",
"url":"video_link",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\""
},
{
"quality":"small",
"itag":"17",
"url":"video_link",
"type":"video\/3gpp; codecs=\"mp4v.20.3, mp4a.40.2\""
}
]
}
Is there any way to combing multiple root nodes or get json output with all streams.
Note :
- Outer foreach loop iterates 5 times in script lifetime
- Inner foreach loop iterates 4 times per each outer foreach loop in script lifetime
Please help me with this as i am new to php. TIA !!!
$video_dataand desired output.