shoprex-icon-big

Shoprex

Developer site for the Wordpress Plugin Shoprex

PHP and WordPress: Get XML Object from url with builtin cache and backup function and check if url is reachable.


GitHub Link: https://gist.github.com/shoprex

/*
* Get XML Object from url with builtin wordpress cache and backup function
* @return object|false
*/
function get_xml_content_by_url( $url, $do_cache = true ) {

	if($do_cache)
		$transient_id = hash("crc32", $url); // Creates short unique ID for WordPress transient function (example: 37531356)
	else
		$transient_id = null;

	$sxi = false;

	if ( ! is_null( $transient_id ) ) {
		// Get Data from Cache
		$sxi = get_transient( 'xml_url_get_' . $transient_id );
	}

	if ( $sxi === false ) {
		// No Cache available or too old

		// Check if url is reachable within a timeout
		$ch = curl_init();
		curl_setopt( $ch, CURLOPT_URL, $url );
		curl_setopt( $ch, CURLOPT_HEADER, true );
		curl_setopt( $ch, CURLOPT_NOBODY, true );
		curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt( $ch, CURLOPT_TIMEOUT, 2 );             // Timeout in Seconds
		$r = curl_exec( $ch );
		curl_close($ch);

		if ( $r == false ) {
			// URL has a timeout

			// Get Data from Backup
			if ( ! is_null( $transient_id ) ) {
				$sxi = get_transient( 'xml_url_get_backup_' . $transient_id  );
			}

			if ( $sxi === false ) {
				// No Backup available exit with false
				return false;
			} else {
				// Backup available, create XML Object
				$sxi = simplexml_load_string( $sxi, 'SimpleXMLIterator' );
			}
		} else {
			// URL is reachable

			// Get new Data from URL (creates XML Object)
			$sxi = new SimpleXmlIterator( $url, null, true );

			// Refresh Data in Cache
			if ( ! is_null( $transient_id ) ) {
				set_transient( 'xml_url_get_' . $transient_id , $sxi->asXML(), 60 * 60 * 24 ); // Store 1 Day
				set_transient( 'xml_url_get_backup_' . $transient_id , $sxi->asXML(), 0 );  // Backup, store forever
			}
		}
	} else {
	// Cache Available, create XML Object
		$sxi = simplexml_load_string( $sxi, 'SimpleXMLIterator' );
	}

	// return Object
	return $sxi;
}

Back

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
*