norfipc.com
Apuntes   Mapa del sitio   Últimas publicaciones

Como insertar contenido de sitios externos con PHP


Impregnar o embeber paginas completas o solo secciones del HTML, en artículos de mi sitio usando PHP. Ejemplos prácticos y código necesario.
Como insertar contenido de sitios externos con PHP
En algunas ocasiones necesitamos insertar el contenido o parte del contenido de una página de internet en un artículo nuestro, de forma que se actualice dinámicamente.
Los métodos disponibles como los marcos o iframe no siempre resuelven la necesidad y con AJAX es imposible agregar contenido de sitios externos, por cuestiones de seguridad.
Tampoco ayuda que dicho sitio no use HTTPS.
Una solución casi perfecta es usar el método DOMDocument::loadHTMLFile de PHP.
En esta página comparto como hacerlo con ejemplos.



Insertar una página externa completa con PHP

La primera posibilidad que nos ofrece el método de PHP es insertar una página completa, con todos sus elementos.
Al final de esta pagina como se puede comprobar, se inserta o impregna el todo contenido de la página Latest Stable Versions que posee los enlaces a todas las versiones de la librería JQuery actualizadas.
Para eso uso el siguiente snippett (código).
<?php
$doc = new DOMDocument();
libxml_use_internal_errors(true); //Evitar mensajes de error de libxml
$doc->loadHTMLFile("https://code.jquery.com/");
echo $doc->saveHTML();
?>
Como se puede comprobar, al cargar todos los elementos de la página externa, también se cargan los archivos de estilo que se suman a los originales de este sitio y cambian completamente la apariencia.



Insertar solo una sección o bloque de una página externa con PHP

Otra opción es impregnar solo una sección de una página externa que puede estar definida por un identificador (ID) o por un elemento HTML.
Nos permite ser más flexibles y es de mucha utilidad cuando se trata de poco contenido, prescindiendo del innecesario.

Insertar contenido de un identificador

El primer código de ejemplo usa un identificador (ID), para insertar solo el contenido que este abarca.
En este caso es un contenedor que posee el identificador "content".
<?php
$texto = new DOMDocument();
$texto->loadHTMLFile("https://code.jquery.com/");
$texto->saveHTML();
$specialdiv = $texto->getElementById('content');
if(isset($specialdiv))
{
  echo $texto->saveXML($specialdiv);
}
?>



Insertar el contenido de una etiqueta HTML

El segundo código de ejemplo permite insertar solo el contenido de una etiqueta HTML (TAG).
La desventaja es que solo se impregna el contenido HTML sin el CSS o sea sin estilo.
En este caso se trata del contenido del elemento <footer>
<?php
$etiqueta = new DOMDocument();
$etiqueta->loadHTMLFile("https://code.jquery.com/");
 $etiqueta->saveHTML();
$seccion = $etiqueta->getElementsByTagName('footer')[0];
if(isset($seccion))
{
    echo $etiqueta->saveXML($seccion);
}
?>



Descarga de JQuery (últimas versiones)

Contenido de la página original.
jQuery CDN
  • jQuery
  • jQuery UI
  • jQuery Mobile
  • Sizzle
  • QUnit
  • Plugins
  • Contribute
    • CLA
    • Style Guides
    • Bug Triage
    • Code
    • Documentation
    • Web Sites
  • Events
    • Support
      • Learning Center
      • IRC/Chat
      • Forums
      • Stack Overflow
      • Commercial Support
    • JS Foundation
      • Join
      • Members
      • Leadership
      • Conduct
      • Donate

    jQuery CDN

    Support the JS Foundation
    • jQuery Core
    • jQuery UI
    • jQuery Mobile
    • jQuery Color
    • QUnit
    • PEP
    <script   src="{{link}}"   integrity="{{hash}}"   crossorigin="anonymous"></script>
    The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

    jQuery CDN – Latest Stable Versions

    Powered by

    jQuery Core

    Showing the latest stable release in each major branch. See all versions of jQuery Core.

    jQuery 3.x

    • jQuery Core 3.6.0 - uncompressed, minified, slim, slim minified

    jQuery 2.x

    • jQuery Core 2.2.4 - uncompressed, minified

    jQuery 1.x

    • jQuery Core 1.12.4 - uncompressed, minified

    jQuery Migrate

    • jQuery Migrate 3.4.0 - uncompressed, minified

    jQuery UI

    Showing the latest stable release for the current and legacy release families. See all versions of jQuery UI.

    jQuery UI 1.13

    • jQuery UI 1.13.1 - uncompressed, minified
    • Themes: base black-tie blitzer cupertino dark-hive dot-luv eggplant excite-bike flick hot-sneaks humanity le-frog mint-choc overcast pepper-grinder redmond smoothness south-street start sunny swanky-purse trontastic ui-darkness ui-lightness vader

    jQuery UI 1.12

    • jQuery UI 1.12.1 - uncompressed, minified
    • Themes: base black-tie blitzer cupertino dark-hive dot-luv eggplant excite-bike flick hot-sneaks humanity le-frog mint-choc overcast pepper-grinder redmond smoothness south-street start sunny swanky-purse trontastic ui-darkness ui-lightness vader

    jQuery Mobile

    Showing the latest stable release for jQuery Mobile. See all versions of jQuery Mobile.

    • jQuery Mobile 1.4.5 - uncompressed, minified, theme (structure only)

    jQuery Color

    Showing the latest stable release for jQuery Color. See all versions of jQuery Color.

    • jQuery Color 2.2.0 - uncompressed, minified
    • jQuery Color SVG Color Names 2.2.0 - uncompressed, minified
    • jQuery Color With Names (last two together) 2.2.0 - uncompressed, minified

    QUnit

    Showing the latest stable release for QUnit. See all versions of QUnit.

    • QUnit 2.19.1 - script, stylesheet

    PEP

    Showing the latest stable release for PEP. See all versions of PEP.

    • PEP 0.4.3 - uncompressed, minified

    Books

    • Learning jQuery 4th Edition by Karl Swedberg and Jonathan Chaffer Learning jQuery Fourth Edition Karl Swedberg and Jonathan Chaffer
    • jQuery in Action by Bear Bibeault, Yehuda Katz, and Aurelio De Rosa jQuery in Action Bear Bibeault, Yehuda Katz, and Aurelio De Rosa
    • jQuery Succinctly by Cody Lindley jQuery Succinctly Cody Lindley
    • Learning Center
    • Forum
    • API
    • Twitter
    • IRC
    • GitHub

    Copyright 2022 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath


    Páginas relacionadas

    ✓ Como escribir con PHP en las páginas web
    ✔ Insertar contenido de otra página con AJAX, JavaScript y JQuery
    ✔ Ejemplos prácticos, trucos y demostraciones de PHP
    ✔ Crear, comprimir o convertir archivos PDF gratis
    ✔ Cargar imágenes desde sitios HTTP no seguros y mostrar con HTTPS
    ✔ Cargar con JavaScript librerías y archivos externos solo a petición

    

    Comparte



    Inicio | Mapa del sitio | Buscar | Sobre mí

    NorfiPC, Copyright © 2022 NorfiPC

    SUBIR