Search code examples
phphtmlwordpresssynchronizationmirror

Pull content from one wordpress site to another wordpress site


I am trying to find a way of displaying the text from a website on a different site.

I own both the sites, and they both run on wordpress (I know this may make it more difficult). I just need a page to mirror the text from the page and when the original page is updated, the mirror also updates.

I have some experience in PHP and HTML, and I also would rather not use Js. I have been looking at some posts that suggest cURL and file_get_contents but have had no luck editing it to work with my sites.

Is this even possible?

Look forward to your answers!


Solution

  • Both cURL and file_get_contents() are fine to get the full html output from an url. For example with file_get_contents() you can do it like this:

    <?php
    
    $content = file_get_contents('http://elssolutions.co.uk/about-els');
    echo $content;
    

    However, in case you need just a portion of the page, DOMDocument and DOMXPath are far better options, as with the latter you also can query the DOM. Below is working an example.

    <?php
    
    // The `id` of the node in the target document to get the contents of 
    $url = 'http://elssolutions.co.uk/about-els';
    $id = 'comp-iudvhnkb';
    
    
    $dom = new DOMDocument();
    // Silence `DOMDocument` errors/warnings on html5-tags
    libxml_use_internal_errors(true);
    // Loading content from external url
    $dom->loadHTMLFile($url);
    libxml_clear_errors();
    $xpath = new DOMXPath($dom);
    
    // Querying DOM for target `id`
    $xpathResultset = $xpath->query("//*[@id='$id']")->item(0);
    
    // Getting plain html
    $content = $dom->saveHTML($xpathResultset);
    
    echo $content;