Access String in PHP

Asked

Viewed 41 times

-2

Good afternoon, I am using the Woocommerce Api to automate my website, but I am having problems when I try to access the answer it sends when I register the product. I send the request to create the product, all normally, but I want to save the id of the product created, for that I need to go through the answer, but the answer that arrives is like this:

public 'response' => 
        object(Automattic\WooCommerce\HttpClient\Response)[8]
          private 'code' => int 201
          private 'headers' => 
            array (size=13)
              ...
          public 'body' => string '{"id":15286,"name":"Produto ABC","slug":"produto-abc-4","permalink":"https:\/\/hrconsultoria.com.br\/teste\/loja\/antartica\/produto-abc-4\/","date_created":"2020-01-31T15:05:18","date_created_gmt":"2020-01-31T18:05:18","date_modified":"2020-01-31T15:05:18","date_modified_gmt":"2020-01-31T18:05:18","type":"simple","status":"publish","featured":false,"catalog_visibility":"visible","description":"Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor qu'... (length=2801)
      private 'responseHeaders' => string

I want to access the id inside 'body', but when access like this:

$teste = (array)$woocommerce->http->response->body;

The error returned is: Trying to get Property 'id' of non-object I tried otherwise:

$teste = (array)$woocommerce->http->response->body;
print_r($teste[0]);

But this way only displays the '{' of the string

How can I scroll through this string to get the product id?

  • 1

    body content is a json, try using json_decode($woocommerce->http->response->body, true); to turn into array.

1 answer

0

The body content is a JSON string. To access the ID, you first need to turn this string into an object:

$body = json_decode($data['response']['body']);

Now, you can access any property of body thus:

echo $body->id; // Imprime o ID
echo $body->name; // Imprime o nome do produto

Browser other questions tagged

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