🌐

Scripts and code examples (PHP and Python)

Documented code ready to use. Each example includes explanation, target audience and problem solved.

💡 How to use these examples: You need a web server (if testing locally, you need Xampp or Docker), PHP 7.4+ installed. Read the explanation block before copying code. Adapt variables (credentials, table names, paths) to your project.
💡 How to use these examples: Make sure you have all Python dependencies installed. Console to run Python commands. All libraries mentioned in the file header.

Web Scraping (transfermarkt.es)

Target audience

Any developer in the world of football.

Problem solved

Obtaining in structured format the list of players of a football team.


# Listado de Librerias, asegurate de instalar todos estos paquetes
import datetime
from datetime import datetime
from bs4 import BeautifulSoup
import requests
import time
import datetime
import json
# Obtener la fecha de hoy
today = datetime.datetime.today()
# Extraer día y mes de la fecha de hoy
day_today = today.day
month_today = today.month
# Extraer el año de la fecha de hoy
current_year = datetime.datetime.now().year
# El año desde donde vamos a iniciar a obtener
# Colocamos el año hasta el que queremos obtener
current_year = datetime.datetime.now().year
current_year = 2020
# Generamos la lista de los años de los que queremos obtener
years_list = list(range(current_year, 1999, -1))
teams = {
  '131': 'fc-barcelona'
}
all_players={}
# Defininimos la URL a obtener datos sustituyendo  el ID de equipo y el nombre en la URL 
# Lo sacaremos de la URL
# TEAM_ID
# TEAM_NAME
# BASE_URL='https://www.transfermarkt.es/fc-barcelona/kader/verein/131/saison_id/2025/plus/1
# BASE_URL='http://www.transfermarkt.es/'+TEAM_NAME+'/kader/verein/'+TEAM_ID+'/plus/1/galerie/0?saison_id='

for team in teams:
  team_name=teams[team]
  all_players[team_name] = []
  BASE_URL='https://www.transfermarkt.es/'+teams[team]+'/kader/verein/'+team+'/saison_id/'
  # Vamos sacando la Plantilla año tras año
  urls = [f"{BASE_URL}{year}/plus/1" for year in years_list]
  # Configuramos las cabeceras del navegador
  headers = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
  }

  all_data_team = []
  for url in urls:
    data = []
    # Para evitar banneos entre temporada y temporada esperamos 20 segundos
    time.sleep(20)
    TRANSFERMARKT_URL = url
    print(TRANSFERMARKT_URL)
    raw_html=None
    html=None
    quotes_body=None
    quotes_tr=None
    rows=None
    response = None
    response = requests.get(TRANSFERMARKT_URL, headers=headers)
    requests.session().close()
    # Analizar sintácticamente el texto fuente HTML guardado en raw_html
    status_code=response.status_code
    if status_code == 200:
      raw_html=response.text
      html = BeautifulSoup(response.text, 'html.parser')
      quotes_html = html.find_all('table', class_="item")
      if not (bool(quotes_html)):
        continue
      quotes_body = html.find_all('tbody')[1]
      quotes_tr = quotes_body.find_all('tr', class_=lambda x: x in ['even', 'odd'])
      count_players=0
      for row in quotes_tr:
        player_data = row.find_all('img', class_=lambda x: x in ['bilderrahmen-fixed lazy lazy'])
        player_data_1 = row.find_all('td', class_=lambda x: x in ['zentriert'])
        birthday_str=player_data_1[1].text[:10]
        
        name = player_data[0].get('title')
        img = player_data[0].get('data-src')        

        all_data_team.append([name,img,birthday_str])
        count_players+=1

# Ya tenemos as plantillas de todas las temporadas y ya tenemos todos los jugadores en un array
  print(all_data_team)
        
🔌

Consume a REST API

Target audience

Developers who need to connect to external services and display data.

Problem solved

HTTP request with cURL, error handling, JSON decoding.

<?php
// Ejemplo: consumir API pública de envío y recepción de mensajes por telegram

    $url="https://api.paginaweb.es"
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPHEADER     => array_merge([
            "Accept: application/json",
            "Content-Type: application/json",
        ], $headers),
        CURLOPT_SSL_VERIFYPEER => true,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error    = curl_error($ch);
    curl_close($ch);

    if ($error) {
        throw new RuntimeException("cURL error: $error");
    }
    if ($httpCode !== 200) {
        throw new RuntimeException("HTTP $httpCode al llamar $url");
    }

    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new RuntimeException("JSON inválido: " . json_last_error_msg());
    }

     print_r($data);

Need a specific script?

If you have a specific automation or integration problem with PHP, tell me about it. I may have already solved it before or we can do it together.

Tell me about your case