Php json undefined property

Undefined property: stdClass::$ AND Trying to get property ‘name’ of non-object Error in plugin

I created a function that reads an external API and it creates a custom post «Job» with some custom fields. For development, I created it in a shortcode and can reload the page to trigger it. Works perfectly. I now am trying to transfer this to a plugin with an options page triggered by a button. When I run the import, I get both errors: Undefined property: stdClass::$jobs_description in /srv/www/careers/public_html/wp-content/plugins/demand-api-remote-old/functions.php on line 89 Trying to get property ‘name’ of non-object in /srv/www/careers/public_html/wp-content/plugins/demand-api-remote-old/functions.php on line 90 The JSON data is this format:

 < //$app_token = $attributes['app_token']; $limit = '100'; $request_uri = 'https://api.hireology.com/v2/public/careers/schompautomotive?page_size=' . $limit; $request = wp_remote_get( $request_uri ); if( is_wp_error( $request ) || '200' != wp_remote_retrieve_response_code( $request ) ) < return; >$jobs = json_decode( wp_remote_retrieve_body( $request ) ); if( empty( $jobs ) ) < return; >ob_start(); // print_array($jobs); foreach( $jobs->data as $jobs ) < $jobs_id = $jobs->id; $jobs_title = $jobs->name; $open_date = $jobs->created_at; $jobs_status = $jobs->status; $jobs_type = $jobs->employment_status; $jobs_description = $jobs->jobs_description; $jobs_family = $jobs->jobs_family->name; $jobsurl = $jobs->career_site_url; $jobs_app_path = $jobs->application_path; foreach ($jobs->locations as $location )< $jobs_location = $location->city; > $jobs_query = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'jobs' )); $post_id = -1; if( null == get_page_by_title($jobs_title, OBJECT, 'jobs') ) < // Insert the post into the database. $post_id = wp_insert_post( array( 'post_type' =>'jobs', 'post_title' => $jobs_title, 'post_content' => $jobs_description, 'post_status' => 'publish', 'post_author' => 1, //'post_category' => array( 8,39 ) )); update_field('field_5cfeb71e121d6', $jobs_id, $post_id); update_field('field_5cfeb738121d7', $jobs_title, $post_id); update_field('field_5d0a57c0c3c62', $open_date, $post_id); update_field('field_5cfeb746121d8', $jobs_status, $post_id); update_field('field_5cfeb769121d9', $jobs_type, $post_id); update_field('field_5cfeb782121da', $jobs_description, $post_id); update_field('field_5cfeb79c121db', $jobs_location, $post_id); update_field('field_5cfeb7ad121dc', $jobs_family, $post_id); update_field('field_5cfeb88cd384c', $jobsurl, $post_id); update_field('field_5cfeb8b7d384d', $jobs_app_path, $post_id); > else < $post_id = -2; >echo '

' .'Jobs Importer Finished' . '

'; > >

The similar code works perfectly without error if I use a shortcode. Can some fill me in on why my objects are not objects? Here is $jobs in dump_var (note I removed data from key «job description» for better readability). I guess the real question is I need help realizing why I can transverse the data in the shortcode, but it changes to an array vs object when I do it through the options page button.

stdClass Object ( [data] => Array ( [0] => stdClass Object ( [id] => 182966 [name] => Client Advisor [created_at] => 2018-03-12T17:56:28.542Z [status] => Open [employment_status] => Full Time - salary [job_description] => [locations] => Array ( [0] => stdClass Object ( [city] => Highlands Ranch [state] => CO ) ) [remote] => [blind_posted] => [job_family] => stdClass Object ( [id] => 1 [name] => Sales [shorten] => 1 [arrange] => 13 ) [careersite_order] => 0 [career_site_url] => https://careers.hireology.com/schompautomotive/182966/description [application_path] => /careers/182966/application [career_site_path] => /schompautomotive/182966/description [organization] => stdClass Object ( [id] => 7587 [name] => Schomp Automotive [type] => Corporate ) [seo_description] => Working at Schomp is more than just an automotive career. Employers may claim to “promote from within,” but we mean it; most of our executive team started as lo. [seo_keywords] => Schomp Automotive, Schomp Automotive jobs, careers at Schomp Automotive, Auto jobs, careers in Auto, Highlands Ranch jobs, Colorado jobs, Sales jobs, Client Advisor [seo_page_title] => Client Advisor | Highlands Ranch, CO | Schomp Automotive [one_click_apply] => [third_party_service_data] => stdClass Object ( [indeed_apply] => stdClass Object ( [indeed-apply-apitoken] => b20e5f8adcfd3b39b7c8cf9d2afae9a143a7f431f32a8011b8f23cf62d59b4e1 [indeed-apply-jobid] => 182966 [indeed-apply-jobtitle] => Client Advisor [indeed-apply-jobcompanyname] => Schomp Automotive [indeed-apply-joblocation] => stdClass Object ( [id] => 1151656 [city] => Highlands Ranch [created_at] => 2019-02-13T00:24:15.575Z [updated_at] => 2019-02-13T00:24:15.575Z [job_id] => 182966 [state_id] => 6 [zip_code] => 80129 [address] => ) [indeed-apply-posturl] => https://app.hireology.com/service_endpoints/job/182966/application_form?ref=career_site&ref_m=indeed+apply [indeed-apply-questions] => https://app.hireology.com/service_endpoints/job/182966/application_form/questions?updated=1530565694 [indeed-apply-phone] => required [indeed-apply-coverletter] => optional [indeed-apply-name] => firstlastname [indeed-apply-jobmeta] => job-meta-button top ) ) ) [1] => stdClass Object ( [id] => 182972 [name] => Certified Service Technician [created_at] => 2018-03-12T18:07:14.816Z [status] => Open [employment_status] => Full Time - salary [job_description] => ''' 

Источник

Читайте также:  Какие средства предоставляет разработчикам html

Fix PHP Notice: Undefined property

This is a guide on how to fix the following PHP notice:

Notice: Undefined property: stdClass::$propertyThatDoesNotExist in /path/to/file.php on line LINE NUMBER

Essentially, this notice will occur if your PHP code attempts to reference an object property that does not exist.

Typos and misspellings.

Firstly, you will need to make sure that you haven’t misspelled the name of the property that you are attempting to reference.

Take the following PHP class as an example:

As you can see, the class above has one property called User::$loggedIn.

Now, let’s do something like this:

$user = new User(); if($user->isLoggedIn)

In the code snippet above, I mistakenly referenced a property called User::$isLoggedIn. The correct name of the property is actually called User::$loggedIn. As a result, the following notice will occur:

Notice: Undefined property: User::$isLoggedIn in /path/to/file.php

The “Undefined property” notice above was caused by a simple misspelling.

While we are on the subject of typos, it is worth pointing out that class properties in PHP are case sensitive. As a result, mistakenly using a capital letter instead of a lowercase letter will also cause this error.

Referencing an object property doesn’t exist yet.

In certain cases, the property that you are attempting to reference might not exist yet. Take the following PHP class as an example:

/** * Class Person */ class Person< /** * Sets the person's name. * * @param $name */ public function setName($name)< $this->name = $name; > >

The class above has one function called setName, which dynamically creates an object property called Person::$name. i.e. The $name property will not exist until the setName function has been called. As a result, the following piece of code will result in an “Undefined property” notice:

$person = new Person(); echo $person->name;

To fix this, we will obviously need to use the setName function before we attempt to access Person::$name:

$person = new Person(); $person->setName('Maria'); echo $person->name;

Check to see if it exists before using it.

If you are unsure about whether an object property exists or not, you can always use the isset function like so:

$person = new Person(); //Using isset to check if a class //property exists or not. if(isset($person->name))< echo $person->name; >

In the PHP code above, we “fixed” the notice by adding an isset check. This works because non-existent class properties equate to null.

This kind of check may be necessary when you are dealing with JSON strings that have been decoded into a PHP object. In the past, I have come across a number of APIs that will add and omit certain JSON fields from their response depending on the circumstances.

Example: If a certain piece of data is missing from a certain record, they may remove the field from the response instead of sending it back with a null or a FALSE value. In cases like this, you will need to make use of the isset function.

Hopefully, this guide helped to clear up some confusion!

Источник

ошибка Undefined property: при парсинге JSON в PHP

в строке foreach($decoded->data as $data) происходит ошибка Notice: Undefined property: stdClass::$data in Warning: Invalid argument supplied for foreach() почему это происходит? с другим файлом всё работает хорошо

else < return $s; >> $urll = "https://gis-api.aiesec.org/v2/opportunities/757492.json?access_token=e316ebe109dd84ed16734e5161a2d236d0a7e6daf499941f7c110078e3c75493&&with_translations=false"; $content = file_get_contents($urll); $clean_content = removeBomUtf8($content); $decoded = json_decode($clean_content); echo ""; foreach($decoded->data as $data) < $title = (string)$data->title; $location = (string)$data->location; $description = (string)$data->description; echo ""; echo sprintf('  ', $title, $location, $description); echo ""; > echo '
%s %s %s
'; ?>

потому что приходит не массив, а один элемент и у него нет data . так что если там иногда все же бывает массив, то следует делать проверку что именно пришло

1 ответ 1

else < return $s; >> $urll = "https://gis-api.aiesec.org/v2/opportunities/757492.json?access_token=e316ebe109dd84ed16734e5161a2d236d0a7e6daf499941f7c110078e3c75493&&with_translations=false"; $content = file_get_contents($urll); $clean_content = removeBomUtf8($content); $decoded = json_decode($clean_content); if(isset($decoded->data) && is_array($decoded->data))< echo ""; foreach($decoded->data as $data) < $title = (string)$data->title; $location = (string)$data->location; $description = (string)$data->description; echo ""; echo sprintf('  ', $title, $location, $description); echo ""; > echo '
%s %s %s
'; >else< $title = (string)$decoded->title; $location = (string)$decoded->location; $description = (string)$decoded->description; echo ""; echo ""; echo sprintf(' ', $title, $location, $description); echo ""; echo '
%s %s %s
'; > ?>

И подумайте над тем, чтобы верстку из php выкинуть, по крайней мере, в таком виде (через echo или в переменных).

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.27.43548

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Addressing «Undefined property: stdClass::» properly

Here is my issue, I am aware why this is happening but, I am unsure how to resolve it as my research on this issue hasn’t returned anything valid to my certain issue. I am making a cURL request and parsing the objects to get their value and then storing it in a variable to insert into a DB later. The HTTP request is from a streaming server. With that said if the stream is not active the object is not present but, if the object is present it is returned like so.

So in my script I have been parsing the object like so to find if the value of the object is true or false then storing that value in a variable to insert into a DB.

$streamStatus = $obj->isConnected?'true':'false'; 

While this works great, it is not correct syntax because when the object is not present due to the stream not being active then I get the following errors in my error log by the dozens.

So my question is, how can I can I properly address this so I can get it’s value of true when it is active and the object is present but false when the object is not present? EDIT Here is the full response if the stream is active and what is returned by the request.

 _definst_ ncopeland rtmp://xx.xxx.xx.xx:xxxxxx false false false true false 2000  

Источник

Оцените статью