Extract information from php json

Asked

Viewed 687 times

0

I’m trying to collect the information contained in "Definition," but I’m having trouble accessing it. (It’s 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']
?>

  • 1

    Could you be more specific? What’s going on?

  • I’m using the urbandictionary api to collect word/expression definitions, and then I went from string to json, only I’m not able to manipulate the array to return the definition

  • is being returned in json? used json_decode?

  • yes, as it is in the code

1 answer

1


I see that when you turn 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 in a foreach for example to recover 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
}
?>
  • It still didn’t work : HTTP ERROR 500

  • Here worked, which error appears to you ?

  • Here also worked.

  • Sorry! I did something wrong here and I ended up changing the code. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.