I managed to get the info needed to create sequential number for CF7 through https://www.banna360.com/contact-from7-dynamic-number-generation/
function wpcf7_generate_rand_number( $wpcf7_data ) {
$properties = $wpcf7_data->get_properties();
$shortcode = '[rand-generator]';
$mail = $properties['mail']['body'];
$mail_2 = $properties['mail_2']['body'];
$subject = $properties['mail']['subject'];
$subject2 = $properties['mail_2']['subject'];
if( preg_match( "/{$shortcode}/", $mail ) || preg_match( "/[{$shortcode}]/", $mail_2 ) ) {
$option = 'wpcf7sg_' . $wpcf7_data->id();
$sequence_number = (int)get_option( $option ) + 1;
update_option( $option, $sequence_number );
$properties['mail']['body'] = str_replace( $shortcode, $sequence_number, $mail );
$properties['mail_2']['body'] = str_replace( $shortcode, $sequence_number, $mail_2 );
$properties['mail']['subject'] = str_replace( $shortcode, $sequence_number, $subject );
$properties['mail_2']['subject'] = str_replace( $shortcode, $sequence_number, $subject2 );
$wpcf7_data->set_properties( $properties );
}
}
add_action( 'wpcf7_before_send_mail', 'wpcf7_generate_rand_number' );
However, I need to specify a start number (eg. 1000001) instead of just starting from 1. Any idea how I do that with this code?
Thanks!
$sequence_number = (int)get_option( $option ) + 1;
if ($sequence_number == 1) {
$sequence_number = 1000001;
}
update_option( $option, $sequence_number );
Related
Im trying to send a MailChimp campaign, from a cron job in a cpanel, in a php file.
The idea is to have a condition and if realized, send a MC campaign.
The test is if there is an unseen message in a certain mailbox with a certain subject. The test is done trough an imap connexion as you will see below.
The unseen email test is working with a cron job, no pb.
But when i add the MC connexion and campaign sending, it is stuck.
Here is the entire code i have tried to write (actually, i tried to use others pieces of code).
Please help if possible.
<?php
//needed for the MailChimp connection
require_once (‘wp-config.php’);
$SCUpdate = 0 ;
$mailbox = imap_open('{imap.server.com:993/imap/ssl}INBOX', 'email#domain.com', 'password');
$unseenMessages = imap_search($mailbox, 'UNSEEN');
if ($unseenMessages != 0) {
$MailHeaders = imap_headers( $unseenMessages );
$Subject = "Subject_Search_Name";
Foreach ($MailHeaders as $Subject) {
$SCUpdate = 1 ;
}
If ($SCUpdate = 1) {
//make the MailChimp connection
function mailchimp_api_request($endpoint,$type=‘POST’,$body = ‘’) {
$api_key = 'xxxxxxx';
$endpoint = ‘https://<dc>.api.mailchimp.com/3.0/’;
list(, $datacenter) = explode( ‘-’, $api_key );
$endpoint = str_replace( ‘<dc>’, $datacenter, $endpoint );
$url = $endpoint . $endpoint;
$request_args = array(
‘method’ => $type,
‘timeout’ => 20,
‘headers’ => array(
‘Content-Type’ => ‘application/json’,
‘Authorization’ => ‘apikey ‘ . $api_key
)
);
if ( $body ) {
$request_args[‘body’] = json_encode( $body );
}
$request = wp_remote_post( $url, $request_args );
$response = is_wp_error( $request ) ? false : json_decode( wp_remote_retrieve_body( $request ) );
return $response;
}
//link campaign to template
$campaign_id = 'xxxxxxx';
function set_mail_campaign_content( $campaign_id, $template_content ) {
$set_content = '';
$set_campaign_content = mailchimp_api_request( "campaigns/$campaign_id/content", 'PUT', $template_content );
if ( $set_campaign_content ) {
if ( ! empty( $set_campaign_content->html ) ) {
$set_content = true;
}
}
return $set_content ? true : false;
}
$list_id = "your-list-id";
$date = date('Y-m-d',strtotime(current_time('mysql')));
$title = "campaign-title";
$subject = "campaign-subject";
$campaign_id = null;
$campaign_id = create_mailchimp_campaign( $list_id, $subject, $title );
if($campaign_id == null){
exit(2);
}
$template_content = array(
'template' => array(
// The id of the template to use.
'id' => xxxxxxx,
)
);
$set_campaign_content = set_mail_campaign_content( $campaign_id, $template_content );
if($set_campaign_content == false){
exit(3);
}
// Schedule time
$time = time();
$schedule = mailchimp_api_request( "campaigns/$campaign_id/actions/schedule", 'POST', array('schedule_time' => $time) );
$campaign = mailchimp_api_request( "/campaigns/$campaign_id", 'GET', '' );
mail('myemail#test.com', 'Test Subject', 'Test Name');
$SCUpdate = 0 ;
}
}
if ($unseenMessages) {
imap_setflag_full( $mailbox, implode(',', $unseenMessages ), '\Seen');
imap_close( $mailbox );
}
?>
This is my code using PHPExcel and NinjaForms. Basically the code does go inside if( isset($sub[$field_key]) ){ so all data is OK. I have also echoed it but somehow the rows are empty.
public function export_file( $form_id ) {
// set xls always on
$use_xls = true;
// set save dir
$upload_dir = wp_upload_dir();
$tmp_file = $upload_dir['basedir'] . '/test/' . $form_id . '/form-submissions-'. $form_id .'.xls';;
$sub_results = $this->get_submissions( $form_id );
$num_submissions = $this->count_submissions($form_id );
$fields_meta = Ninja_Forms()->form($form_id)->get_fields();
$field_names=array();
$header_row=array();
$header_row['id'] = __('ID','ninja-forms-spreadsheet');
$header_row['date_submitted'] = __('Submission date','ninja-forms-spreadsheet');
foreach($fields_meta as $field_id => $field){
$field_settings = $field->get_settings();
// skip save fields
if( $field_settings['type'] == 'save' || $field_settings['type'] == 'submit' ) {
unset( $fields_meta[$field_id] );
continue;
}
$field_names[$field_id] = sanitize_title( $field_settings['label'].'-'.$field_id );
$field_types[$field_id] = $field_settings['type'];
$header_row[$field_id] = $field_settings['label'];
}
//die();
require_once( plugin_dir_path( __DIR__ ).'/ninja-forms-excel-export/includes/PHPExcel.php');
$objPHPExcel = new PHPExcel();
$row_number = 1;
// this should be the same wordpress uses and therefore be the saver choice
PHPExcel_Shared_File::setUseUploadTempDirectory( true );
// Table Headline
$col_index = 0;
foreach ($header_row as $headline) {
$col = PHPExcel_Cell::stringFromColumnIndex( $col_index );
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValue( $headline );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)->getFont()->setBold(true);
$col_index++;
}
$objPHPExcel->getActiveSheet()->freezePane( "A2" );
$row_number++;
/*
* Loop over each sub
*/
foreach($sub_results as $sub){
$col = 'A';
$objPHPExcel->getActiveSheet()->getCell($col++.$row_number)->setValueExplicit( $sub['_seq_num'], PHPExcel_Cell_DataType::TYPE_NUMERIC );
$objPHPExcel->getActiveSheet()->getCell($col++.$row_number)->setValueExplicit( $sub['date_submitted'] );
$col_index = 0;
foreach ($fields_meta as $field_id => $field) {
$field_key = '_field_'.$field_id;
if( isset($sub[$field_key]) ){
$field_value = $sub[$field_key];
$col = PHPExcel_Cell::stringFromColumnIndex( 2+$col_index );
$field_value = maybe_unserialize( $field_value );
echo $field_types[$field_id] . ' ';
if( in_array($field_types[$field_id], array( 'shipping', 'total', 'number' ) ) ){ // float values
$objPHPExcel->getActiveSheet()->getCell($col.$row_number) ->setValueExplicit( $field_value, PHPExcel_Cell_DataType::TYPE_NUMERIC );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getNumberFormat()
->setFormatCode('#,##');
}elseif( in_array($field_types[$field_id], array( 'starrating', 'quantity' ) ) ){ // integer values
$objPHPExcel->getActiveSheet()->getCell($col.$row_number) ->setValueExplicit( $field_value, PHPExcel_Cell_DataType::TYPE_NUMERIC );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getNumberFormat()
->setFormatCode('#');
}elseif( in_array($field_types[$field_id], array( 'checkbox' ) ) || strpos($field_types[$field_id], '-optin') ){
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( $field_value, PHPExcel_Cell_DataType::TYPE_STRING );
}elseif( in_array($field_types[$field_id], array( 'listcheckbox' ) ) ){
$field_output = $field_value;
if( is_array($field_value) ){
$field_output = '';
foreach ($field_value as $key => $value) {
if( $field_output == '' )
$field_output = $value;
else
$field_output .= ', ' . $value;
}
}
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_output,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
}elseif( $field_types[$field_id] == 'file_upload' ){
if( is_array($field_value)){
$field_value = implode("\n", $field_value);
}
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_value,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getAlignment()
->setWrapText(true);
}elseif( $field_types[$field_id] == 'textarea' ){
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_value,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getAlignment()
->setWrapText(true);
}else{
if( is_array($field_value) ){
$field_value = implode('; ', $field_value);
}
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_value,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
}
}
$col_index++;
}
$row_number++;
}
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
ob_end_clean();
$objWriter->save($tmp_file);
}
The excel modified time is updated correctly but all rows are empty except the first header row in bold. I am not sure what is the issue.
Any help is appreciated.
Hi i've been trying to generate the following XML with PHP.
I've managed to generate it all except for the location section as it seems to treat it as another root and error out. Does anyone know the correct way to produce this?
<?xml version="1.0" encoding="UTF-8"?>
<classifieds xmlns="http://www.bdjjobs.com/ClassifiedJobFromRecruiterFeed">
<job>
<reference_id>20161114-72</reference_id>
<recruiter>Smiles R Us</recruiter>
<job_title>Denture Specialist</job_title>
<short_description><![CDATA[An exciting position in a dynamic dental practice]]></short_description>
<description><![CDATA[<p>Full description of post</p>]]></description>
<location>
<city>city</city>
<state>county</state>
<country>country</country>
</location>
<salary_description><![CDATA[Full Package]]></salary_description>
<organisations>Independent Dental Practice</organisations>
<job_type>Specialist Appointments</job_type>
<salary_band>£100,000 or more</salary_band>
<contract_type>Associate Permanent</contract_type>
<hours>Full time</hours>
<practice_type>Mixed (NHS/Private)</practice_type>
<start_date>2016-09-01</start_date>
<expiry_date>2016-10-30</expiry_date>
<application_email>apply_here#email.com</application_email>
</job>
</classifieds>
Any assistance would be greatly appreciated, thanks :)
Here is the code:
// Start Job Element
$job_element = $xml_document->createElement("job");
// Job ID
$rootreferencenumber = $xml_document->createElement("reference_id");
$rootreferencenumber->appendChild($xml_document->createCDATASection( get_the_ID() ));
$job_element->appendChild($rootreferencenumber);
// Recruiter
$recruiter = $xml_document->createElement("recruiter");
$recruiter->appendChild($xml_document->createCDATASection( "MBR Dental Recruitment" ));
$job_element->appendChild($recruiter);
// Job title
$title = $xml_document->createElement("title");
$title->appendChild($xml_document->createCDATASection( get_the_title() ) );
$job_element->appendChild($title);
// Job Description
$description = $xml_document->createElement("description");
$description->appendChild($xml_document->createCDATASection( ( strip_tags( str_replace( "</p>", "\n\n", get_the_content() ) ) ) ) );
$job_element->appendChild($description);
// City
$city = $xml_document->createElement("city");
$get_city = explode( ',', get_post_meta( get_the_ID(), 'geolocation_city', true ) );
$city->appendChild($xml_document->createCDATASection( $get_city[0] ) );
$job_element->appendChild($city);
// Region from Taxonomy
$region = $xml_document->createElement("region");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_region', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$job_element->appendChild($region);
// Create Company Name
$company_name = $xml_document->createElement("organisations");
$company_name->appendChild($xml_document->createCDATASection('xx'));
$job_element->appendChild($company_name);
// Create Phone Number
$phone_number = $xml_document->createElement("phone_number");
$phone_number->appendChild($xml_document->createCDATASection('0000'));
$job_element->appendChild($phone_number);
// Job direct URL
$url = $xml_document->createElement("application_url");
$url->appendChild($xml_document->createCDATASection(get_permalink( get_the_ID() )));
$job_element->appendChild($url);
// Category
$phone_number = $xml_document->createElement("job_type");
$phone_number->appendChild($xml_document->createCDATASection('Job'));
$job_element->appendChild($phone_number);
// Subcategory
$region = $xml_document->createElement("subcategory");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_category', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$job_element->appendChild($region);
// Job date based on todays date
$date = $xml_document->createElement("start_date");
$date->appendChild($xml_document->createCDATASection(date(Ymd) ));
$job_element->appendChild($date);
// Job date expire from original post date
$expiry_date = $xml_document->createElement("expiry_date");
$wpDate = (date(Ymd) );
$wpDate = new DateTime($wpDate);
$wpDate->add(new DateInterval('P14D')); // P14D means a period of 14 days
$wpDate = $wpDate->format('Ymd');
$expiry_date->appendChild($xml_document->createCDATASection( $wpDate ));
$job_element->appendChild($expiry_date);
// Create Application Email Address
$app_email = $xml_document->createElement("application_email");
$app_email->appendChild($xml_document->createCDATASection('xx#xx.com'));
$job_element->appendChild($app_email);
// End Job Element
$root->appendChild($job_element);
Ok so i was approaching this completely wrong..
I needed to append the child elements (City + Region) to the new $location element. Not to the original $job_element
here is the correct code:
// Start Job Element
$job_element = $xml_document->createElement("job");
// Job ID
$rootreferencenumber = $xml_document->createElement("reference_id");
$rootreferencenumber->appendChild($xml_document->createCDATASection( get_the_ID() ));
$job_element->appendChild($rootreferencenumber);
// Recruiter
$recruiter = $xml_document->createElement("recruiter");
$recruiter->appendChild($xml_document->createCDATASection( "xx" ));
$job_element->appendChild($recruiter);
// Job title
$title = $xml_document->createElement("title");
$title->appendChild($xml_document->createCDATASection( get_the_title() ) );
$job_element->appendChild($title);
// Job Description
$description = $xml_document->createElement("description");
$description->appendChild($xml_document->createCDATASection( ( strip_tags( str_replace( "</p>", "\n\n", get_the_content() ) ) ) ) );
$job_element->appendChild($description);
//Create Location Element
$location = $xml_document->createElement("location");
$job_element->appendChild($location);
// City
$city = $xml_document->createElement("city");
$get_city = explode( ',', get_post_meta( get_the_ID(), 'geolocation_city', true ) );
$city->appendChild($xml_document->createCDATASection( $get_city[0] ) );
$location->appendChild($city);
// Region from Taxonomy
$region = $xml_document->createElement("region");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_region', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$location->appendChild($region);
// Country Code
$country = $xml_document->createElement("country");
$country->appendChild($xml_document->createCDATASection('UK'));
$location->appendChild($country);
// Create Company Name
$company_name = $xml_document->createElement("organisations");
$company_name->appendChild($xml_document->createCDATASection('xx'));
$job_element->appendChild($company_name);
// Create Phone Number
$phone_number = $xml_document->createElement("phone_number");
$phone_number->appendChild($xml_document->createCDATASection('xx'));
$job_element->appendChild($phone_number);
// Job direct URL
$url = $xml_document->createElement("application_url");
$url->appendChild($xml_document->createCDATASection(get_permalink( get_the_ID() )));
$job_element->appendChild($url);
// Category
$job_type = $xml_document->createElement("job_type");
$job_type->appendChild($xml_document->createCDATASection('Job'));
$job_element->appendChild($job_type);
// Subcategory
$region = $xml_document->createElement("subcategory");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_category', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$job_element->appendChild($region);
// Job date based on todays date
$date = $xml_document->createElement("start_date");
$date->appendChild($xml_document->createCDATASection(date(Ymd) ));
$job_element->appendChild($date);
// Job date expire from original post date
$expiry_date = $xml_document->createElement("expiry_date");
$wpDate = (date(Ymd) );
$wpDate = new DateTime($wpDate);
$wpDate->add(new DateInterval('P14D')); // P14D means a period of 14 days
$wpDate = $wpDate->format('Ymd');
$expiry_date->appendChild($xml_document->createCDATASection( $wpDate ));
$job_element->appendChild($expiry_date);
// Create Application Email Address
$app_email = $xml_document->createElement("application_email");
$app_email->appendChild($xml_document->createCDATASection('x#xx.net'));
$job_element->appendChild($app_email);
// End Job Element
$root->appendChild($job_element);
I made a plugin that converts any uri to a hyperlink, if it finds hyper-link it will ignore it and only convert the no hyper-links uri.
In the plugin admin page I set two options, first to convert links only for the front-end, and the second option is to convert uri when ever a post/comment saved to database.
// permanently means before save to database
if ( $this->plugin_options['uri2links_convert_method'] == 'permanently' ) {
add_action( 'wp_insert_post_data', array($this, 'make_post_url_clickable' ) );
//add_action( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
else {
add_filter( 'the_content', array($this, 'make_post_url_clickable' ) );
//add_filter( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
My problem here if I set the plugin option to convert uri for front-end it will ignore hyper-links and convert the other uri, but if I set it to convert before save to database it 'll not ignore hyper-links and treat them as normal uri witch make the results look like this:
<a class="sdf" href=" <a href="http://test.test-75.1474.stackoverflow.com/" >http://test.test-75.1474.stackoverflow.com/ </a>
<a class="sdf" href=" <a href="https://www.stackoverflow.com" >https://www.stackoverflow.com </a>
The complete plugin source code:
<?php
/*
Plugin name: URIs to a click-able links
Plugin URI:
Description: Convert URI's to a click-able links
Author: h Abdou
Author URI: habdou.me
Version: 1.0
*/
// The admin page for the plugin
require_once( 'uri2links-menu.php' );
class Uri2Links {
protected $css = '';
protected $rel = '';
protected $target = '';
protected $convert_links = '';
protected $convert_emails = '';
protected $plugin_options = array();
protected $url_match_pattern = '/[a-zA-Z0-9\.\/\?\:#\-_=#]+\.([a-zA-Z0-9\.\/\?\:#\-_=#])+/';
protected $email_match_pattern = '/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/';
//protected $links_match_pattern = '/<a(?:"[^"]*"[\'"]*|\'[^\']*\'[\'"]*|[^\'">])+>^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$<\/a>/';
protected $links_match_pattern = '/<a[^>]*>(.*?)<\/a>/';
protected $links_matched = array();
public function __construct() {
//$this->plugin_options = get_option( 'uri2links_plugin_options' );
$this->plugin_options = array( 'uri2links_convertLinksEmails' => array( 'Links', 'Emails' ), 'uri2links_convert_method' => 'permanently' );
$this->css = isset( $this->plugin_options['uri2links_custom_css'] ) ? ' class="' . $this->plugin_options['uri2links_custom_css'] . '"' : '';
$this->rel = isset( $this->plugin_options['uri2links_rel_attr'] ) ? ' rel="' . $this->plugin_options['uri2links_rel_attr'] . '"' : '';
if ( isset( $this->plugin_options['uri2links_open_links_method'] ) && $this->plugin_options['uri2links_open_links_method'] == 'new')
$this->target = ' target="_blank"';
$this->convert_links = isset( $this->plugin_options['uri2links_convertLinksEmails'][0] ) ? $this->plugin_options['uri2links_convertLinksEmails'][0] : '';
$this->convert_emails = isset( $this->plugin_options['uri2links_convertLinksEmails'][1] ) ? $this->plugin_options['uri2links_convertLinksEmails'][1] : '';
if ( $this->plugin_options['uri2links_convert_method'] == 'permanently' ) {
add_action( 'wp_insert_post_data', array($this, 'make_post_url_clickable' ) );
//add_action( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
else {
add_filter( 'the_content', array($this, 'make_post_url_clickable' ) );
//add_filter( 'preprocess_comment', array($this, 'make_comment_url_clickable' ) );
}
// The admin page for the plugin
new Uri2LinksMenu;
}
// Convert all URI in a post to hyper-links.
public function make_post_url_clickable( $content ) {
$links = $this->hash_links( $content );
if ( $this->convert_links == 'Links' ) {
$content = preg_replace($this->url_match_pattern, ' <a href="\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content);
}
if ( $this->convert_emails == 'Emails' ) {
$content = preg_replace($this->email_match_pattern, ' <a href="mailto:\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content);
}
// Replace back the hashed 'a' tags to the original status.
foreach ( $links as $link_hash => $link_text ) {
$content = str_replace( $link_hash, $link_text, $content );
}
return $content;
}
// Same as 'make_post_url_clickable' but this for comments
public function make_comment_url_clickable( $content ) {
$links = hash_links( $content['comment_content']['comment_content'] );
if ( $this->convert_links == 'Links' ) {
$content['comment_content'] = preg_replace($this->url_match_pattern, ' <a href="\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content['comment_content']);
}
if ( $this->convert_emails == 'Emails' ) {
$content['comment_content'] = preg_replace($this->email_match_pattern, ' <a href="mailto:\\0"' . $this->css . $this->rel . $this->target . ' >\\0</a> ', $content['comment_content']);
}
foreach ( $links as $link_hash => $link_text ) {
$content['comment_content'] = str_replace( $link_hash, $link_text, $content['comment_content'] );
}
return $content;
}
// hash all 'a' tags so 'make_*_url_clickable' will ignore them.
public function hash_links( &$content ) {
$links = array();
if ( preg_match_all( $this->links_match_pattern, $content, $matches ) ) {
$array_size = sizeof( $matches[0] );
for ( $i = 0; $i < $array_size; ++$i ) {
$link_hash = md5( $matches[0][$i] );
$links[$link_hash] = $matches[0][$i];
$content = str_replace( $matches[0][$i], $link_hash, $content );
}
}
//die('hash_links called!');
return $links;
}
}
new Uri2Links;
?>
I just want to mention that WordPress already got the make_clickable() function that takes text uri to HTML links.
To activate it for the post content we only need this simple plugin:
<?php
/** Plugin Name: Make text uri to HTML links in the post content **/
add_filter( 'the_content', 'make_clickable', 9 );
By default this function runs on the comment text:
add_filter( 'comment_text', 'make_clickable', 9 );
I have the following code:
$data = file_get_contents('http://www.robotevents.com/robot-competitions/vex-robotics-competition?limit=all');
echo "Downloaded";
$dom = new domDocument;
#$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');
$rows = $tables->item(2)->getElementsByTagName('tr');
foreach ($rows as $row) {
$cols = $row->getElementsByTagName('td');
for ($i = 0; $i < $cols->length; $i++) {
echo $cols->item($i)->nodeValue . "\n";
}
}
The final field has an Link which I need to store the URL of. Also, The script outputs characters such as "Â". Does anyone know how to do/fix these things?
I would recommend not using DOM to parse HTML, as it has problems with invalid HTML. INstead use regular expression
I use this class:
<?php
/**
* Class to return HTML elements from a HTML document
* #version 0.3.1
*/
class HTMLQuery
{
protected $selfClosingTags = array( 'area', 'base', 'br', 'hr', 'img', 'input', 'link', 'meta', 'param' );
private $html;
function __construct( $html = false )
{
if( $html !== false )
$this->load( $html );
}
/**
* Load a HTML string
*/
public function load( $html )
{
$this->html = $html;
}
/**
* Returns elements from the HTML
*/
public function getElements( $element, $attribute_match = false, $value_match = false )
{
if( in_array( $element, $this->selfClosingTags ) )
preg_match_all( "/<$element *(.*)*\/>/isU", $this->html, $matches );
else
preg_match_all( "/<$element(.*)>(.*)<\/$element>/isU", $this->html, $matches );
if( $matches )
{
#Create an array of matched elements with attributes and content
foreach( $matches[0] as $key => $el )
{
$current_el = array( 'name' => $element );
$attributes = $this->parseAttributes( $matches[1][$key] );
if( $attributes )
$current_el['attributes'] = $attributes;
if( $matches[2][$key] )
$current_el['content'] = $matches[2][$key];
$elements[] = $current_el;
}
#Return only elements with a specific attribute and or value if specified
if( $attribute_match != false && $elements )
{
foreach( $elements as $el_key => $current_el )
{
if( $current_el['attributes'] )
{
foreach( $current_el['attributes'] as $att_name => $att_value )
{
$keep = false;
if( $att_name == $attribute_match )
{
$keep = true;
if( $value_match == false )
break;
}
if( $value_match && ( $att_value == $value_match ) )
{
$keep = true;
break;
}
elseif( $value_match && ( $att_value != $value_match ) )
$keep = false;
}
if( $keep == false )
unset( $elements[$el_key] );
}
else
unset( $elements[$el_key] );
}
}
}
if( $elements )
return array_values( $elements );
else
return array();
}
/**
* Return an associateive array of all the form inputs
*/
public function getFormValues()
{
$inputs = $this->getElements( 'input' );
$textareas = $this->getElements( 'textarea' );
$buttons = $this->getElements( 'button' );
$elements = array_merge( $inputs, $textareas, $buttons );
if( $elements )
{
foreach( $elements as $current_el )
{
$attribute_name = mb_strtolower( $current_el['attributes']['name'] );
if( in_array( $current_el['name'], array( 'input', 'button' ) ) )
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['attributes']['value'] ) )
$form_values[$attribute_name] = $current_el['attributes']['value'];
}
else
{
if( isset( $current_el['attributes']['name'] ) && isset( $current_el['content'] ) )
$form_values[$attribute_name] = $current_el['content'];
}
}
}
return $form_values;
}
/**
* Parses attributes into an array
*/
private function parseAttributes( $str )
{
$str = trim( rtrim( trim( $str ), '/' ) );
if( $str )
{
preg_match_all( "/([^ =]+)\s*=\s*[\"'“”]{0,1}([^\"'“”]*)[\"'“”]{0,1}/i", $str, $matches );
if( $matches[1] )
{
foreach( $matches[1] as $key => $att )
{
$attribute_name = mb_strtolower( $att );
$attributes[$attribute_name] = $matches[2][$key];
}
}
}
return $attributes;
}
}
?>
Usage is:
$c = new HTMLQuery();
$x = $c->getElements( 'tr' );
print_r( $x );