Search code examples
phpcurlsvgdomxpath

Getting external SVG object using PHP cURL


I'm trying to show a server status on my webpage that is being shown as a SVG object. (for example [http://downdetector.com/status/netflix).

However i can't seem to get it. I got anything from bad request errors to empty objects or empty divs. What i did succeed in however is returning the entire page using cURL, but i fumbled when trying to filter out the rest and only print te SVG.

How can i trick the external server into thinking i'm a browser, and successfully and preferably elegantly retrieve a working SVG object and printing it on my page? I'm still quite new to PHP so any explanation next to the code would be very welcome.

I even tried to use Simple HTML DOM, but i still havent been able to get the desired results.

This is my current code (messy as it still may be) :

<?php
    class StatusController { 

    function __construct() {
       //include('assets/simple_html_dom.php');
    }

    public function getStatus() { 
        $ch = curl_init();
                curl_setopt($ch,CURLOPT_URL,"http://downdetector.com/status/netflix");
                curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
                $output=curl_exec($ch);

                curl_close($ch);
                //print $output;    
                // $html = str_get_html($output);
                // $elem = $html->find('div[id=holder]', 0);
                // print $elem;
                // 
                $dom = new DOMDocument();
                $dom->loadHTML($output); // Returned $data from CURL request

                $xpath = new DOMXPath($dom);
                $elements = $xpath->query('*/div'); // Don't know how to fill in this query to find an ID
                echo('<pre>'.print_r($elements, true).'</pre>');
                var_dump($elements);

            } 

} 
?>

I've been trying lots of options for nearly 3 full days now and i really don't know what to do at this point.


Solution

  • The problem with this URL is, that the SVG is loaded dynamically via JavaScript:

    <p>Netflix offers an on-demand streaming video service through the internet as well as a flat rate DVD by mail service. </p>
              <img id='tracker' style='display: none' />
    <script type='text/javascript'>
    // <![CDATA[
      url = '//tracker.downdetector.com/count/company/20065.txt?ref=' + encodeURIComponent(document.referrer);
      $('#tracker')[0].src = url;
    // ]]>
    </script>
    

    The script part will be replaced by the SVG. I can't tell you, how to get it in this case.

    But if you have a website with normal imbedded SVG elements, you should be able to select them by $elements = $xpath->query("//*[name()='svg']");.