ø Don’t waste your time reading this blog ø

Weird characters when parsing CSV in PHP

Filed under: web 2.0 — Tags: , — taewoo @ 7:37 pm February 2, 2010

For some reason, if you do this PHP

$csv_file = file_get_contents(site_url($file_name));
$csv_lines = explode(”n”, $csv_file);

a CSV line like this

Campaign Name    Ad Group Name    Component Type    …

turns into a weird line like this:

377376C^@a^@m^@p^@a^@i^@g^@n ^@N…

This has to do with PHP’s character encoding issues.

Here’s the easier way to take care of this problem:

$csv1 = file($csv_file);
$csv2 = implode($csv1);
$csv3 = iconv(”UTF-16″,”ISO-8859-1″,$csv2);
$csv = explode (”n”,$csv3);

This will solve that character issue.

Related Blogs

[Post to Twitter] Tweet This Post 

How to search for html TITLE tag with PHP

Filed under: web 2.0 — Tags: — taewoo @ 12:24 pm June 27, 2009

I know this is probably a lame post, but i’ll do it anyway.

If you want to search for HTML title, you’ll notice everyone gives out an answer like this:

$matches = array();
$pattern = ‘/<title>(.*)<\/title>/’;
preg_match($pattern, $html, $matches);

$pagetitle = $matches[1];

But this actually doesn’t work in cases where there’s extra newline character. (.*) Doesn’t match new lines, which probably causes the problem. This means that it matches

<title> title </title>

but doesn’t match

<title> title
</title>

Instead, do this:

preg_match(”/<title>([^<]*)<\/title>/i”, $html_text, $title);

[Post to Twitter] Tweet This Post