Search code examples
phpregexphp4

PHP: how to load file from different server as string?


I am trying to load an XML file from a different domain name as a string. All I want is an array of the text within the < title >< /title > tags of the xml file, so I am thinking since I am using php4 the easiest way would be to do a regex on it to get them. Can someone explain how to load the XML as a string? Thanks!


Solution

  • You could use cURL like the example below. I should add that regex-based XML parsing is generally not a good idea, and you may be better off using a real parser, especially if it gets any more complicated.

    You may also want to add some regex modifiers to make it work across multiple lines etc., but I assume the question is more about fetching the content into a string.

    <?php
    
    $curl = curl_init('http://www.example.com');
    
    //make content be returned by curl_exec rather than being printed immediately                                 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    
    $result = curl_exec($curl);
    
    if ($result !== false) {
        if (preg_match('|<title>(.*)</title>|i', $result, $matches)) {
            echo "Title is '{$matches[1]}'";   
        } else {
            //did not find the title    
        }
    } else {
        //request failed
        die (curl_error($curl)); 
    }