-1

I am attempting to get a JSON feed output from attributes of an XML feed. I can get the data out of the XML, however, I am unable to get it to format correctly. The error seems to be with the json_encode not adding the curly braces to the outputted date. This is the code I have so far:

<?php

    $url = 'http://cloud.tfl.gov.uk/TrackerNet/LineStatus';

    if(!$xml = simplexml_load_file($url))
    {
        die("No xml for you");
    }

    $linestatus = array();

    foreach ($xml->LineStatus as $line)
    {
        echo $line->Line['Name'];
        echo $line->Status['Description'];
    }

    header('Content-Type: application/json');
    print_r(json_encode($linestatus));

?>
JohnRobertPett
  • 1,133
  • 4
  • 21
  • 36

3 Answers3

0

The echos are screwing everything up. I think you intend to append to linestatus which remains empty per your code.

$linestatus[] = array(
    "name" => $line->Line['Name'],
    "description" => $line->Status['Description']
);

You also need to use echo instead of print_r to actually emit the JSON.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

You are declaring $linestatus as an array, then never put anything in it before finally encoding it and trying to output it. Of course it won't work as expected! Instead, you should be populating it with values:

$linestatus = array();

foreach ($xml->LineStatus as $line)
{
    $linestatus[] = $line->Line;
}

header('Content-Type: application/json');
print_r(json_encode($linestatus));
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
0

The problem is that you're not storing the name and description into the array.

Try this:

foreach ($xml->LineStatus as $line)
{
    $linestatus[] =  array('name' => $line->Line['Name']);
    $linestatus[] =  array('description' => $line->Line['Description']);
}

Demo!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150