Extract information from json php [duplicate]

0

I'm trying to collect the information contained in "definition", but I'm having trouble accessing it. (This is my first time working with API and PHP)

{
    "tags": [
        "hi",
        "hi",
        "hey",
        "hey",
        "greeting",
        "greeting",
        "yo",
        "yo",
        "goodbye",
        "goodbye"
    ],
    "result_type": "exact",
    "list": [
        {
            "definition": "what you say when your talking casually with friends and your mom walks in the room",
            "permalink": "http://hello.urbanup.com/69266",
            "thumbs_up": 3528,
            "author": "mad at the world",
            "word": "hello",
            "defid": 69266,
            "current_vote": "",
            "example": "What the hell(mom enters)-o mom.",
            "thumbs_down": 975
        },
        {
            "definition": "The only word on this site that has nothing to do with [sex] or [drugs]!",
            "permalink": "http://hello.urbanup.com/2269237",
            "thumbs_up": 2123,
            "author": "pirates"
        }
    ]
}

    

$json = file_get_html('http://api.urbandictionary.com/v0/define?term=hello')->plaintext;
$json = json_decode($json);
echo $json['definition']
?>
    
asked by anonymous 28.12.2017 / 19:15

1 answer

1

I see that when you transform the file into json it becomes an object with other properties internally.

The variable $json is an object. You can access its properties in this way: $objeto->propriedade .

' definition ' is inside ' list' ($ json-> list), which is an array of objects. You can walk it through a foreach for example to retrieve the property.

<?php
//include_once('../simple_html_dom.php');

$json = file_get_contents('http://api.urbandictionary.com/v0/define?term=hello');
$json = json_decode($json);
$list = $json->list;

foreach ($list as $list_item) {
    echo("definition: ".$list_item->definition.PHP_EOL); //PHP_EOL quebra de linha
}
?>
    
28.12.2017 / 19:39