Search code examples
phpsimplexml

simplexml_load_file() issues within PHP class


So I'm trying to use a class I found to fix an eCommerce problem I have.

Original Blog Post

In Washington State online stores need to determined a tax rate based on the shipping address.

WA Sales Tax Rate Lookup URL Interface

Class:

/**
 * @author SmallDog
 * @contact [email protected]
 * @created 01-27-2011 
**/

class destinationTax
{
    private $dor_url = 'http://dor.wa.gov';

    function __construct(){ }

    function getTax($addr,$city,$zip)
    {
        $req = $this->dor_url."/AddressRates.aspx?output=xml&addr=$addr&city=$city&zip=$zip";
        return $this->_get_decoded($req);
    }

    private function _get_decoded($url)
    {
        $url = urlencode($url);
        if($xml = simplexml_load_file($url))
        {
            switch($xml->attributes()->code)
            {
                case 0:
                    // Code 0 means address was perfect
                    break;
                case 1:
                    $xml->msg = "Warning: The address was not found, but the ZIP+4 was located.";
                    break;
                case 2:
                    $xml->msg = "Warning: Neither the address or ZIP+4 was found, but  the 5-digit ZIP was located.";
                    break;
                case 3:
                    $xml->msg = "Error: The address, ZIP+4, and ZIP could not be found.";
                    break;
                case 4:
                    $xml->msg = "Error: Invalid arguements.";
                    break;
                case 5:
                    $xml->msg = "Error: Internal error.";
            }
        }
        else $xml = "Error: Could not load XML.";

        return  $xml;
    }
}

Useage:

$tax = new destinationTax;
$tax = $tax->getTax("123 Main Street", "Kirkland", "98033");
echo $tax->attributes()->rate;

Error:

Warning: simplexml_load_file() [function.simplexml-load-file]: URL file-access is disabled in the server configuration in /.../.../classes.php

Warning: simplexml_load_file(http://dor.wa.gov/AddressRates.aspx?output=xml&addr=123+Main+Street&city=Kirkland&zip=98033) [function.simplexml-load-file]: failed to open stream: no suitable wrapper could be found in /.../.../classes.php

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http%3A%2F%2Fdor.wa.gov%2FAddressRates.aspx%3Foutput%3Dxml%26addr%3D123+Main+Street%26city%3DKirkland%26zip%3D98033" in /.../.../classes.php

Fatal error: Call to a member function attributes() on a non-object in /.../.../tax.php


Solution

  • Your server does not support remote file access. If you have cURL access, you could get the XML data that way, as exampled below:

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($curl);
    
    $xml = simplexml_load_string($data);
    
    // ...