PHP Get XML from Remote URL with HTTP Authentication

后端 未结 5 1848
太阳男子
太阳男子 2021-01-14 02:21

I have a URL which gives an xml output. It requires a username and password which I can access through a browser using the format:

http://username:pa

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 03:13

    For XML with basic auth URL try this

    $username = 'admin';
    $password = 'mypass';
    $server = 'myserver.com';
    
    $context = stream_context_create(array(
            'http' => array(
                'header'  => "Authorization: Basic " . base64_encode("$username:$password")
            )
        )
    );
    $data = file_get_contents("http://$server/", false, $context);
    $xml=simplexml_load_string($data);
    if ($xml === false) {
        echo "Failed loading XML: ";
        foreach(libxml_get_errors() as $error) {
            echo "
    ", $error->message; } } else { print_r($xml); }

提交回复
热议问题