0

I've been trying to figure out how to get the value of 'text' in this array using PHP and after many attempts, I've not got to the stage of giving up.

Can somebody tell me how to get the translated text in 'text' from this array? It's returned from using the REST API on Microsoft Azure Translator Service and is a JSON object according to documentation, but no matter what I try I can't get any of the text from any part of the array using code. A pointer would be very much appreciated before I lose what hair I have left!

Array
(
    [0] => stdClass Object
        (
            [detectedLanguage] => stdClass Object
                (
                    [language] => en
                    [score] => 1
                )
            [translations] => Array
                (
                    [0] => stdClass Object
                        (
                            [text] => Entrez votre texte ici
                            [to] => fr
                        )
                )
        )
)

 
Nick Smith
  • 311
  • 1
  • 8
  • 1
    Does this answer your question? [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – El_Vanja May 12 '21 at 13:36

1 Answers1

5

Objects are accessed by arrows -> and arrays are accessed by square brackets [] in PHP.

You can see each is labelled as stdClass Object or Array. So work down the response as so:

$response[0]->translations[0]->text

To break it down...

$response[0]

stdClass Object
    (
        [detectedLanguage] => stdClass Object
            (
                [language] => en
                [score] => 1
            )
        [translations] => Array
            (
                [0] => stdClass Object
                    (
                        [text] => Entrez votre texte ici
                        [to] => fr
                    )
            )
    )

$response[0]->translations

            Array
            (
                [0] => stdClass Object
                    (
                        [text] => Entrez votre texte ici
                        [to] => fr
                    )
            )

$response[0]->translations[0]

                stdClass Object
                    (
                        [text] => Entrez votre texte ici
                        [to] => fr
                    )

$response[0]->translations[0]->text

                Entrez votre texte ici

I hope that weird example helps!

Djave
  • 8,595
  • 8
  • 70
  • 124
  • Thanks, that was exactly what I wasn't managing to figure out - after a long day of going around in circles! – Nick Smith May 13 '21 at 01:14