How to print to console from a php file in wordpress - php

I have a php file which is part of a wordpress plugin. I need to debug an issue we are having. I want to find out what a variable's value is. How can I print the variable's value to console? echo or chrome or firefox extensions have been suggested. I couldn't get echo to output to console (echo “$variablename";) and neither using the firephp extension for firefox.

To answer your question, you can do this:
echo '<script>console.log("PHP error: ' . $error . '")</script>';
but I would recommend doing one of the things #Ishas suggested instead. Make sure $error doesn't contain anything that can mess up your script.

If you are thinking about the javascript console, you can not do this from PHP.
You have a few options you could choose from:
echo
var_dump
create a log file
xdebug
For a quick check for a variables value I would use var_dump, it will also show you the data type of the variable. This will be output to the browser when you request the page.

Logging to the DevTools console from PHP in WordPress
Here you can see my solution for the problem in action while debugging coupon logic in WooCommerce. This solution is meant for debug purposes, only. (Note: Screenshot not up to date, it will also expose private members.)
Features
Allow printing before and after rendering has started
Works in front-end and back-end
Print any amount of variables
Encode arrays and objects
Expose private and protected members of objects
Also log to the log file
Safely and easily opt-out in the production environment (in case you keep the calls)
Print the caller class, function and hook (quality of life improvement)
Solution
wp-debug.php
function console_log(): string {
list( , $caller ) = debug_backtrace( false );
$action = current_action();
$encoded_args = [];
foreach ( func_get_args() as $arg ) try {
if ( is_object( $arg ) ) {
$extract_props = function( $obj ) use ( &$extract_props ): array {
$members = [];
$class = get_class( $obj );
foreach ( ( new ReflectionClass( $class ) )->getProperties() as $prop ) {
$prop->setAccessible( true );
$name = $prop->getName();
if ( isset( $obj->{$name} ) ) {
$value = $prop->getValue( $obj );
if ( is_array( $value ) ) {
$members[$name] = [];
foreach ( $value as $item ) {
if ( is_object( $item ) ) {
$itemArray = $extract_props( $item );
$members[$name][] = $itemArray;
} else {
$members[$name][] = $item;
}
}
} else if ( is_object( $value ) ) {
$members[$name] = $extract_props( $value );
} else $members[$name] = $value;
}
}
return $members;
};
$encoded_args[] = json_encode( $extract_props( $arg ) );
} else {
$encoded_args[] = json_encode( $arg );
}
} catch ( Exception $ex ) {
$encoded_args[] = '`' . print_r( $arg, true ) . '`';
}
$msg = '`📜`, `'
. ( array_key_exists( 'class', $caller ) ? $caller['class'] : "\x3croot\x3e" )
. '\\\\'
. $caller['function'] . '()`, '
. ( strlen( $action ) > 0 ? '`🪝`, `' . $action . '`, ' : '' )
. '` ➡️ `, ' . implode( ', ', $encoded_args );
$html = '<script type="text/javascript">console.log(' . $msg . ')</script>';
add_action( 'wp_enqueue_scripts', function() use ( $html ) {
echo $html;
} );
add_action( 'admin_enqueue_scripts', function() use ( $html ) {
echo $html;
} );
error_log( $msg );
return $html;
}
wp-config.php (partially)
// ...
define( 'WP_DEBUG', true );
// ...
/** Include WP debug helper */
if ( defined( 'WP_DEBUG' ) && WP_DEBUG && file_exists( ABSPATH . 'wp-debug.php' ) ) {
include_once ABSPATH . 'wp-debug.php';
}
if ( ! function_exists( 'console_log' ) ) {
function console_log() {
}
}
/** Sets up WordPress vars and included files. */
require_once( ABSPATH . 'wp-settings.php' );
Usage
Before the HTML <head> is rendered:
console_log( $myObj, $myArray, 123, "test" );
After the HTML <head> is rendered (in templates, etc. / use when the above does not work):
echo console_log( $myObj, $myArray, 123, "test" );
Output format
📜 <caller class>\<caller function>() 🪝 <caller action/hook> ➡️ <variables ...>
Special thanks to
Andre Medeiros for the property extraction method

You can write a utility function like this:
function prefix_console_log_message( $message ) {
$message = htmlspecialchars( stripslashes( $message ) );
//Replacing Quotes, so that it does not mess up the script
$message = str_replace( '"', "-", $message );
$message = str_replace( "'", "-", $message );
return "<script>console.log('{$message}')</script>";
}
The you may call the function like this:
echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" );
and this will output to console like this:
Error Message: This is really a -unique- problem!
Notice the quotes replaced with "-". It is done so that message does not mess up your script as pointed by #Josef-Engelfrost
You may also go one step further and do something like this:
function prefix_console_log_message( $message, $type = "log" ) {
$message_types = array( 'log', 'error', 'warn', 'info' );
$type = ( in_array( strtolower( $type ), $message_types ) ) ? strtolower( $type ) : $message_types[0];
$message = htmlspecialchars( stripslashes( $message ) );
//Replacing Quotes, so that it does not mess up the script
$message = str_replace( '"', "-", $message );
$message = str_replace( "'", "-", $message );
return "<script>console.{$type}('{$message}')</script>";
}
and call the function like this:
echo prefix_console_log_message( "Error Message: This is really a 'unique' problem!" , 'error');
It will output error in console.

Related

Change the variable value in an other plugin function with PHP

I try to change a class, which is stored in a variable without making any changes in the plugin file. I'm not sure how to target the variable inside the function.
This is the function: function learndash_mark_complete( $post, $atts = array() ) { Inside this function, there is a variable called $button_class.
if ( isset( $atts['button']['class'] ) ) {
$button_class = ' class="learndash_mark_complete_button ' . esc_attr( $atts['button']['class'] ) . '" ';
} else {
$button_class = ' class="learndash_mark_complete_button" ';
}
Is there a simple way to change the code to..
if ( isset( $atts['button']['class'] ) ) {
$button_class = ' class="myclass' . esc_attr( $atts['button']['class'] ) . '" ';
} else {
$button_class = ' class="myclass" ';
}
without change the plugin file. Maybe to create a function in functions.php or in a seperate (new) plugin?
I saw articles on the internet about add_filter, but I'm not sure how to target the part I need without wipe the whole function.
I know I could change the class with jQuery or something, and maybe it should be a lot easier, but I like to learn new things.
If plugin does not provide filter hook to change the class name then you can not you filter value.
But, if you are writing your own plugin then you can use this type of logic to change the value without touching original source.
This code should be in the plugin file,
$arrayToFilter = array(
'class_name' => 'learndash_mark_complete_button',
'key1' => 'value1', // So on
);
$value = apply_filters( 'change_class', $arrayToFilter );
if ( isset( $atts['button']['class'] ) ) {
$button_class = ' class="'.$value['class_name'].'' . esc_attr( $atts['button']['class'] ) . '" ';
} else {
$button_class = ' class="'.$value['class_name'].'" ';
}
And add this filter into theme functions.php file to modify change_class hook's value
function example_callback($args) {
// Here you can get $arrayToFilter as $args
$args['class_name'] = 'myclass';
return $args;
}
add_filter( 'change_class', 'example_callback',10 , 1 ); // Where $priority is 10, $accepted_args is 1.
I hope you got basic idea of add_filter().

Cannot use a scalar value as an array in my PHP

I am actually just started to learn PHP and I use wordpress. I put this code but seems something wrong in it. It shows warning message : Cannot use a scalar value as an array. Can you guys help me with this. Its pretty annoying when I see the warning message on the add new product under the product data table.
Oh, I am using PHP 7.1 now.
I've tried to fix it using PHP checker and searching through the search engine but since I am a beginner, I couldn't find anything that can help.
/**
* Localizes a script, only if the script has already been added.
*
* #since 2.1.0
*
* #param string $handle Name of the script to attach data to.
* #param string $object_name Name of the variable that will contain the data.
* #param array $l10n Array of data to localize.
* #return bool True on success, false on failure.
*/
public function localize( $handle, $object_name, $l10n ) {
if ( $handle === 'jquery' ) {
$handle = 'jquery-core';
}
if ( is_array( $l10n ) && isset( $l10n['l10n_print_after'] ) ) { // back compat, preserve the code in 'l10n_print_after' if present.
$after = $l10n['l10n_print_after'];
unset( $l10n['l10n_print_after'] );
}
foreach ( (array) $l10n as $key => $value ) {
if (! is_scalar( $value ) ) {
continue;
}
$l10n[ $key ] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8' );
}
$script = "var $object_name = " . wp_json_encode( $l10n ) . ';';
if ( ! empty( $after ) ) {
$script .= "\n$after;";
}
$data = $this->get_data( $handle, 'data' );
if ( ! empty( $data ) ) {
$script = "$data\n$script";
}
return $this->add_data( $handle, 'data', $script );
}
Just want to see the warning message not showing up again.
Thanks in advance

Cut a string/url to always get a final string/url with a specific data and it's value in php

I have an url that contain the word "&key".
The "&key" word can be at the beginning or at the end of our url.
Ex1= http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxx&c4=xxx&f1=xxx
Ex2= http://xxxxx.com?c1=xxx&key=xxx&c2=xxx&c3=xxx&c4=xxx&f1=xxx
What I would like to get is all the time the url with the Key element and it's value.
R1: http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxx
R2: http://xxxxx.com?c1=xxx&key=xxx
Here is what I have done:
$lp_sp_ad_publisher = "http://xxxxx.com?c1=xxx&c2=xxx&c3=xxx&key=xxxc4=xxxf1=xxx";
$lp_sp_ad_publisher_cut_link = explode("&", $lp_sp_ad_publisher_cut[1]); // tab
$lp_sp_ad_publisher_cut_link_final = $lp_sp_ad_publisher_cut_link[0]; // http://xxxxx.com?c1=xxx
$counter = 1;
// finding &key inside $lp_sp_ad_publisher_cut_link_final
while ((strpos($lp_sp_ad_publisher_cut_link_final, '&key')) !== false);
{
$lp_sp_ad_publisher_cut_link_final .= $lp_sp_ad_publisher_cut_link[$counter];
echo 'counter: ' . $counter . ' link: ' . $lp_sp_ad_publisher_cut_link_final . '<br/>';
$counter++;
}
I'm only looping once all the time. I guess the while loop isn't refreshing with the inside new value. Any solution?
EDIT: Sorry, I misunderstood the question.
This is tricky because the url key and value can be anything, so it might be safer to breakdown the URL using a combination of parse_url() and parse_str(), then put the url back together leaving off the part you don't want. Something like this:
function cut_url( $url='', $key='' )
{
$output = '';
$parts = parse_url( $url );
$query = array();
if( isset( $parts['scheme'] ) )
{
$output .= $parts['scheme'].'://';
}
if( isset( $parts['host'] ) )
{
$output .= $parts['host'];
}
if( isset( $parts['path'] ) )
{
$output .= $parts['path'];
}
if( isset( $parts['query'] ) )
{
$output .= '?';
parse_str( $parts['query'], $query );
}
foreach( $query as $qkey => $qvalue )
{
$output .= $qkey.'='.$qvalue.'&';
if( $qkey == $key ) break;
}
return rtrim( $output, '&' );
}
Usage:
$input = 'https://www.xxxxx.com/test/path/index.php?c1=xxx&c2=xxx&key=xxx&c3=xxx&c4=xxx&f1=xxx';
$output = cut_url( $input, 'key' );
Output:
https://www.xxxxx.com/test/path/index.php?c1=xxx&c2=xxx&key=xxx
If the intention is to always ensure that the parameter key and it's associated value appear at the end of the string, how about something like:
$tmp=array();$key='';
$parts=explode( '&', parse_url( $_SERVER['REQUEST_URI'], PHP_URL_QUERY ) );
foreach( $parts as $pair ) {
list( $param,$value )=explode( '=',$pair );
if( $param=='key' )$key=$pair;
else $tmp[]=$pair;
}
$query = implode( '&', array( implode( '&', $tmp ), $key ) );
echo $query;
or,
parse_str( $_SERVER['QUERY_STRING'], $pieces );
foreach( $pieces as $param => $value ){
if( $param=='key' ) $key=$param.'='.$value;
else $tmp[]=$param.'='.$value;
}
$query = implode( '&', array( implode( '&', $tmp ), $key ) );
update
I'm puzzled that you were "not getting the good result"!
consider the url:
https://localhost/index.php?sort=0&dir=false&tax=23&cost=99&aardvark=creepy&key=banana&tree=large&ac=dc&limit=1000#569f945674935
The above would output:
sort=0&dir=false&tax=23&cost=99&aardvark=creepy&tree=large&ac=dc&limit=1000&key=banana
so the key=banana gets placed last using either method above.

Two different WordPress hooks with the same callback

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 );

Is there something in this code block that would stop execution?

I am parsing a webpage and following the links in order to map links from one page to another. I am only pulling the title of the page the link is on, the URL used to link the pages, and the title of the page the URL leads to.
My code works smoothly to discover the links I am interested in and descends subpages to find additional product links. There are a few hundred of these across at least a hundred pages, so it's several HTML files of parsing. I am building an in the form $products[index] contains is an array array(['url'] => URLToPage, ['title'] => TitleOfPage, ['link_title'] => TitleOfLinkedPage) as I hope this demonstrates.
The script works fine until I add this snippet, after which the script will stop execution with no errors, warnings, notices or anything; it simply never reaches the end of the script. I have included set_time_limit(0) to prevent execution time from expiring as this script takes some time to complete. This code is executed after the $products array has been populated, if any links found, and $products is always an array, and I have outputted the $link_html_strings in test cases to verify that the pages are being retrieved as expected. This is the offending code:
// Populate the destination link titles
if ( isset( $products ) && count( $products ) > 0 )
{
foreach( $products as $id => $product )
{
$from_this_page = $product['url'];
if ( $DEBUG ) echo 'Parsing ' . $from_this_page . '.<br />';
$link_html_string = file_get_contents( $from_this_page, NULL, NULL, NULL, 500 );
$string_parts = explode( '<title>', $link_html_string );
$string_parts = explode( '</title>', $string_parts[1] );
$products[$id]['link_title'] = $string_parts[0];
if ( $DEBUG ) echo 'Found title: ' . $products[$id]['link_title'] . '<br />';
ob_flush();
flush();
}
}
There should never really be 500 characters needed, however, I had some concern with memory usage when reading the entire files so I reduced the load (I think) by limiting the read. I thought perhaps the script was using up all the allocated memory for PHP. When this is included, it will iterate through this loop several times but at some point stop execution, this point is not also exactly the same. I will get several echo for what file is being parsed.
This is the full code for the script, included to answer questions regarding contents of $products in comments.
<?php
// PHP HTML DOM Parser from http://simplehtmldom.sourceforge.net/
require_once( 'includes/simple_html_dom.php' );
//error_reporting( E_ALL );
set_time_limit( 0 );
// Debugging flag
$DEBUG = false;
function reportProducts( $category, $products )
{
echo '<table width="90%" align="center"><tr><th colspan="3">';
echo $category . ' has ' . count( $products ) . ' products listed, or in subpages.';
echo '</th></tr>';
echo '<tr><td bgcolor="#777777" width="30%">This page</td>
<td bgcolor="#bbbbbb" width="30%">links with</td>
<td bgcolor="#777777" width="30%">to this page</td></tr>';
foreach( $products as $product )
{
echo '<tr><td bgcolor="#777777">' . $product['title'] . '</td>
<td bgcolor="#bbbbbb"><a href="' . $product['url'] . '">' . $product['url'] .
'</a></td><td bgcolor="#777777">' . $product['link_title'] . '</td></tr>';
}
echo '</table><br />';
ob_flush(); // Server may buffer again, preventing incremental display
flush();
}
function parseProductsForPage( $page_to_parse )
{
global $DEBUG;
$failed = false;
$product_id = 0;
$page_dom = new simple_html_dom();
$page_html_string = #file_get_contents( $page_to_parse->href );
$load_state = #$page_dom->load( $page_html_string );
if ( $load_state === NULL )
{
// Find any direct product pages for this page
if ( $DEBUG ) echo $page_to_parse->href . ' being checked for products... ';
$possible = $page_dom->find( 'a[onclick]' );
foreach( $possible as $link )
{
if ( $link->innertext == "[ Add to cart ]" )
{
$products[$product_id]['url'] = $link->href;
$titles = $page_dom->find( 'title' );
$products[$product_id]['title'] = $titles[0]->innertext;
$product_id++;
}
}
if ( $DEBUG )
{
if ( isset( $products ) )
{
echo count( $products ) . ' found on page.<br />';
} else
{
echo '0 found on page.<br />';
}
}
// Find subpages...
if ( $DEBUG ) echo $page_to_parse->href . ' being checked for links... ';
$subpages = $page_dom->find( 'a[class=buy]' );
if ( $DEBUG ) echo count( $subpages ) . ' found.<br />';
// ... and parse
foreach( $subpages as $subpage )
{
$subpage_dom = new simple_html_dom();
$subpage_html_string = #file_get_contents( $subpage->href );
$load_state = #$subpage_dom->load( $subpage_html_string );
if ( $load_state === NULL )
{
// Find any direct product pages for this page
if ( $DEBUG ) echo $subpage->href . ' being checked for products... ';
$possible = $subpage_dom->find( 'a[onclick]' );
foreach( $possible as $link )
{
if ( $link->innertext == "[ Add to cart ]" )
{
$products[$product_id]['url'] = $link->href;
$titles = $page_dom->find( 'title' );
$products[$product_id]['title'] = $titles[0]->innertext;
$product_id++;
}
}
if ( $DEBUG )
{
if ( isset( $products ) )
{
echo count( $products ) . ' found on page.<br />';
} else
{
echo '0 found on page.<br />';
}
}
$subpage_dom->clear();
} else
{
$failed[] = $subpage->href;
}
$subpage_dom->clear();
unset( $subpage_dom );
}
// Populate the destination link titles
if ( isset( $products ) && count( $products ) > 0 )
{
foreach( $products as $id => $product )
{
// $from_this_page = $product['url'];
// if ( $DEBUG ) echo 'Parsing ' . $from_this_page . '.<br />';
// $link_html_string = file_get_contents( $from_this_page, NULL, NULL, NULL, 500 );
// $string_parts = explode( '<title>', $link_html_string );
// $string_parts = explode( '</title>', $string_parts[1] );
// $products[$id]['link_title'] = $string_parts[0];
// if ( $DEBUG ) echo 'Found title: ' . $products[$id]['link_title'] . '<br />';
// ob_flush();
// flush();
}
}
} else
{
$failed[] = $page_to_parse->href;
}
$titles = $page_dom->find( 'title' );
if ( isset( $products ) ) reportProducts( $titles[0]->innertext, $products );
$page_dom->clear();
unset( $page_dom );
return $failed;
}
// Initialize the object
$html = new simple_html_dom();
$html->load_file( 'index.html' );
// Start output buffer
ob_start();
// Find all product categories listed on the website
if ( $DEBUG ) echo '<h1>Collecting links from LHN...</h1>';
$sidelinks = $html->find( 'a[class=sidelink_main]' );
$html->clear();
unset( $html );
echo '<h1>Found ' . count( $sidelinks ) . ' categories.</h1><br />';
ob_flush(); // Server may buffer output, preventing incremental display
flush();
// Find links and products for each category
foreach( $sidelinks as $sidelink )
{
if ( $DEBUG ) echo 'Sending ' . $sidelink->href . ' to parser.<br />';
$parse_failed = parseProductsForPage( $sidelink );
if ( $parse_failed )
{
foreach( $parse_failed as $failure )
{
$failures[] = $failure;
}
}
}
echo count( $failures ) . ' pages failed to parse.<br />';
echo '<br />FIN!<br />'; // Easily searched to verfiy end of script was reached, also
// celebratory.
ob_end_flush(); // Clear output buffer
flush();
?>
Are you sure that set_time_limit has any effect (when running php with safe_mode on it will not have any effect )?
Also be sure that $string_parts = explode( '<title>', $link_html_string ); gives an result(there may be no title-element or the tagName may be used uppercase)

Categories