1

I am trying to extract a segment from the json file of Rome2Rio API with PHP but I cant get an output.

The json file from rome2rio:

{
    "serveTime": 1,
    "places": [
        { "kind": "town", "name": "Kozani", "longName": "Kozani, Greece", "pos": "40.29892,21.7972", "countryCode": "GR", "regionCode": "ESYE13" },
        { "kind": "city", "name": "Thessaloniki", "longName": "Thessaloniki, Greece", "pos": "40.64032,22.93527", "countryCode": "GR", "regionCode": "ESYE12" }
    ],
    "airports": [],
    "airlines": [],
    "aircrafts": [],
    "agencies": [{
            "code": "KTEL",
            "name": "KTEL",
            "url": "http://www.ktelbus.com/?module=default\u0026pages_id=15\u0026lang=en",
            "iconPath": "/logos/Trains/KTELgr.png",
            "iconSize": "27,23",
            "iconOffset": "0,0"
        }
    ],
    "routes": [
            { "name": "Bus", "distance": 121.04, "duration": 120, "totalTransferDuration": 0, "indicativePrice": { "price": 9, "currency": "EUR", "isFreeTransfer": 0 },
            "stops": [
                { "name": "Kozani", "pos": "40.30032,21.79763", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" },
                { "name": "Thessaloniki", "pos": "40.6545,22.90233", "kind": "station", "countryCode": "GR", "timeZone": "Europe/Athens" }
        ]

The PHP code I wrote is:

$json_rome2rio = file_get_contents("http://free.rome2rio.com/api/1.2/json/Search?key=&oName=kozani&dName=thessaloniki");
$parsed_json_r = json_decode($json_rome2rio);
echo $parsed_json_r->agencies->name;
Manom18x
  • 85
  • 7
  • Json_decode returns an associative array_filter not an object? Try `echo $parsed_json_r ['agencies']['name'];` –  Sep 26 '15 at 22:55
  • 2
    Also, seems like it could be a copy-paste error but, your JSON is missing some `]` and `}` –  Sep 26 '15 at 23:03
  • If you are sure that the json you receive is valid (the example you posted is not as Terminus pointed out): [Read on here](http://stackoverflow.com/a/29308899/2912456) or edit your question to be more specific(`I cant get an output.` is rather broad). edit: Possible Hint: agencies is an array. – Rangad Sep 26 '15 at 23:50
  • You are correct, I thought that this is not an array. – Manom18x Sep 27 '15 at 06:52

1 Answers1

1

The agencies property contains an array of agencies (note the square brackets). To access the name as you're after, you can do the following:

echo $parsed_json_r->agencies[0]->name;

This assumes that at least one agency is returned and that the agency you are after is the first one if more than one is returned.

John C
  • 8,223
  • 2
  • 36
  • 47