See also with only JavaScript: JSON and Fetch in JavaScript: A Practical Guide with Pokémon API Examples
Choose Your Pokémon:
Define Pokémon API URL
$pokemonListUrl = 'https://pokeapi.co/api/v2/pokemon/';
This line sets the URL of the Pokémon API endpoint that provides a list of Pokémon.
Fetch Pokémon List
$response = file_get_contents($pokemonListUrl);
The file_get_contents function is used to retrieve the content of the specified URL ($pokemonListUrl). In this case, it fetches the list of Pokémon in JSON format.
Decode JSON Response
$data = json_decode($response, true);
The json_decode function is used to decode the JSON response into a PHP associative array. The true parameter is passed to ensure that the JSON is decoded into an associative array rather than an object.
Generate HTML Options Dynamically:
foreach ($data['results'] as $pokemon) { $pokemonName = ucfirst($pokemon['name']); echo ""; }
This loop iterates through the array of Pokémon obtained from the API response ($data[‘results’]). For each Pokémon, it extracts the name, capitalizes the first letter using ucfirst, and dynamically generates an HTML
The resulting HTML might look like this:
<option value='https://pokeapi.co/api/v2/pokemon/1'>Bulbasaur</option> <option value='https://pokeapi.co/api/v2/pokemon/2'>Ivysaur</option> <!-- ... and so on for each Pokémon in the list -->
Full Code
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Pokémon Selector</title><style>body {font-family: Arial, sans-serif;}#pokemonInfo {max-width: 600px;margin: 20px auto;}img {max-width: 100%;height: auto;}h2 {color: #f00;}h3 {color: #00f;}</style></head><body><h2>Select a Pokémon:</h2><select id="pokemonSelector"><?php// PHP code to fetch Pokémon list and generate options dynamically$pokemonListUrl = 'https://pokeapi.co/api/v2/pokemon/';$response = file_get_contents($pokemonListUrl);$data = json_decode($response, true);foreach ($data['results'] as $pokemon) {$pokemonName = ucfirst($pokemon['name']);echo "<option value='{$pokemon['url']}'>$pokemonName</option>";}?></select><div id="pokemonInfo"><!-- Pokémon details will be displayed here --></div><script>// Function to fetch and display details of the selected Pokémonasync function fetchAndDisplayPokemonDetails() {const pokemonSelect = document.getElementById('pokemonSelector');const selectedPokemonUrl = pokemonSelect.value;try {const response = await fetch(selectedPokemonUrl);const pokemonDetails = await response.json();// Displays Pokémon detailsconst pokemonInfoContainer = document.getElementById('pokemonInfo');pokemonInfoContainer.innerHTML = buildPokemonInfoHTML(pokemonDetails);} catch (error) {console.error('Error during the request:', error);}}// Function to build the HTML for Pokémon detailsfunction buildPokemonInfoHTML(data) {// Pokémon Name and IDconst pokemonTitle = `<h2>${data.name.charAt(0).toUpperCase() + data.name.slice(1)} (ID: ${data.id})</h2>`;// Pokémon Imageconst pokemonImage = `<img src="${data.sprites.front_default}" alt="${data.name}">`;// Pokémon Typesconst types = data.types.map(type => type.type.name).join(', ');const pokemonTypes = `<h3>Type(s): ${types}</h3>`;// Pokémon Abilitiesconst abilities = data.abilities.map(ability => ability.ability.name).join(', ');const pokemonAbilities = `<h3>Abilities: ${abilities}</h3>`;// Pokémon Statsconst stats = data.stats.map(stat => `<p><strong>${stat.stat.name}:</strong> ${stat.base_stat}</p>`).join('');// Pokémon Weightconst weight = `<p><strong>Weight:</strong> ${data.weight / 10} kg</p>`; // Converting from hectograms to kilograms// Building the final HTMLconst finalHTML = pokemonTitle + pokemonImage + pokemonTypes + pokemonAbilities + stats + weight;return finalHTML;}// Adds an event listener to load Pokémon details upon selectionconst pokemonSelect = document.getElementById('pokemonSelector');pokemonSelect.addEventListener('change', fetchAndDisplayPokemonDetails);</script></body></html>