Jump to content

Importing JSON to pages - updating existing page/deleting


nsc
 Share

Recommended Posts

Hi all,

I'm still relatively new to the PW world and needed a little help.

I've been looking into how to import JSON into new pages and have managed to get that working fine (through help of others posts on the forum).

I've got it checking if the page exists (not sure if it's the right way), but am stuck when it comes to updating the page (if it exists).

Also, completely stuck when it comes to deleting the page -- if it's not in the JSON anymore.

Can anyone help me out/point me in the right direction?

<?php
	
	$movies = json_decode(file_get_contents('http://www.omdbapi.com/?s=smart&page=1&apikey=xxxxxx'));

	foreach ($movies->Search as $movie) {

		$exists = $pages->get("name=$movie->imdbID");
			
		if($exists->id) {
			echo $exists->id . ' already exists <br>';
		} else {
			$p = new Page();
			$p->template = 'single-movie';
			$p->parent = wire('pages')->get('/movies/');
			$p->name = $movie->imdbID;
			$p->title = ucfirst($movie->Title);
			$p->save();

			// populate fields
			$p->event_id = $movie->imdbID;
			$p->movie_original_title = ucfirst($movie->Title);
			$p->movie_image_url = $movie->Poster;
			$p->save();

			echo $p->title . ' added <br>';
			
		}

	}

?>

 

Link to comment
Share on other sites

2 hours ago, nsc said:

but am stuck when it comes to updating the page (if it exists).

Well, you would first check if the IMDB fields (content) is identical to your already existing page content / fields. If not, skip the update. If one or more fields don't have matching values, update the PW page field(s) that have changed.

  • Like 1
Link to comment
Share on other sites

3 hours ago, nsc said:

Thanks for this guys, so would you just re-save the page or is there another method to update?

You can assign the fields again and save again just like you are doing right now, there's also just field saving like this:

$page->some_field = "new value";

$page->save('some_field');

In this scenario I think either is just fine, just useful to know when you get into hooks and stuff like that ?

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...