convert html to php code, more of less

ultimatebuster 0 Tallied Votes 182 Views Share

This script is something i wrote during work, as I often need to do this (concatenate strings via multiple lines so it's clearer). Hopefully you guys like it.

def htmlToPHP(varname, html):
    if type(varname) != str:
        raise TypeError("varname must be string.")

    if type(html) == list or type(html) == tuple:
        for line in html:
            line = addslash(line)
            print "%s .= \"%s\\n\";" % (varname, line)
    elif type(html) == str:
        htmlToPHP(varname, html.split("\n"))
    else:
        raise TypeError("html must be string or list of strings")

def addslash(string):
    string = string.strip()
    i = 0
    while i < len(string):
        index = string.find('"', i)
        if index != -1:
            string = string[0:index] + "\\" + string[index:]
        else:
            break
        
        i = index + 2

    return string


t = '''<a href="test.php">some link</a>
<h1 class="small">Something</h1>'''

htmlToPHP("$txt", t)

# outputs:
# $txt .= "<a href=\"test.php\">some link</a>\n";
# $txt .= "<h1 class=\"small\">Something</h1>\n";
TrustyTony 888 pyMod Team Colleague Featured Poster

Had to code it myself to understand what it does better, here my simple version. It could be put to function with parameters t and var, of course. I left out the unpythonic type stuff. I understand your desire of flexibility, but maybe readability suffers.

t = '''<a href="test.php">some link</a>
<h1 class="small">Something</h1>'''
var = "$txt"

for outp in ('%s .= \"%s\\n\";' %(var, line.replace('"','\\"')) for line in t.split('\n')):
    print outp

# outputs:
# $txt .= "<a href=\"test.php\">some link</a>\n";
# $txt .= "<h1 class=\"small\">Something</h1>\n";
ultimatebuster 14 Posting Whiz in Training

that is definitely almost unreadable!

I'm not a big fan of the (for ...)

but then i did forgot about replace(), but it would cause a problem, as does mine addslash, which i'm fixing

Example of the problem: if i already have a slash before the ", it would add another one.

Fixed:

def htmlToPHP(varname, html):
    if type(varname) != str:
        raise TypeError("varname must be string.")

    if type(html) == list or type(html) == tuple:
        for line in html:
            line = addslash(line)
            print "%s .= \"%s\\n\";" % (varname, line)
    elif type(html) == str:
        htmlToPHP(varname, html.split("\n"))
    else:
        raise TypeError("html must be string or list of strings")

def addslash(string):
    string = string.strip()
    i = 0
    while i < len(string):
        index = string.find('"', i)
        if index != -1: 
            if string[index-1] == "\\":
                i = index + 1
                continue
            
            string = string[0:index] + "\\" + string[index:]
        else:
            break

        i = index + 2

    return string
Dcurvez 0 Junior Poster in Training

okay..LOL

i have been basically ORDERED (LOL) to learn PHP..and really I dont know ANYTHING about it..but the reason for this new order from the upper rings of the corporate ladder is too build web sites with (which i have yet too do as well)

anyway to get to the question here
lol
can anyone post a working version for VB.net???

GoodLuckChuck 0 Junior Poster in Training

I learned html to put up my website. I think that most websites use html. What advantage does php have over html? Is it better for the websites that have forums where people are leaving their own messages on the website. That is just a guess but I do know that most forums use a different code than html.

Does this website use php? The source code for this site says "<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0" Is php a type of html? I saw that this is under Python. The only thing that I know about python is that it is a non-venemous snake that kills by constriction.

TrustyTony 888 pyMod Team Colleague Featured Poster

Here my fixed for already \" version in functions:

def quote_backslach(line):
    result = ''
    find = '"'
    while find:
        start,find,line = line.partition(r'\"')
        result += start.replace('"',r'\"')+find
    return result

def toPHP(var, t):
    for outp in ((r'%s .= "%s\n";' %
                  (var, quote_backslach(line)))
                 for line in t.split('\n') if line): ## eliminates empty lines
        yield outp

print '\n'.join(toPHP("$txt",'''
<a href=\\"test.php">some link</a>
<h1 class="small">Something</h1>
'''))

The split ignores empty lines to allow better formatting for multiline string.

Dcurvez 0 Junior Poster in Training

well, as far as i have been told (and I am sure it is limited information)
is that PHP has an advantage over html for the use of forms and such.

but..
I really am not so sure that it is such an advantage with all of the new apps out today.

today, i have yet to hear of one real-un argumentative advantage of using PHP over html (*sees a battle start to emerge*)

ultimatebuster 14 Posting Whiz in Training

PHP and HTML is really 2 different technology. HTML is necessary to create a website. PHP is a good dynamic HTML generator, really.

@tonyjv, cuts a lot of lines, list comprehension definitely kills readability.

TrustyTony 888 pyMod Team Colleague Featured Poster

@tonyjv, cuts a lot of lines, list comprehension definitely kills readability.

I do not use list comprehensions, only two generators and function to separate quoting action our of the generator. Raw string kills some \\'s. Now there is nothing complicated in the generator only the splitting ignoring empty lines with if.

Notice that '\n'.join takes readily generator as well as list.

Here little cleaner version returning generator instead of yielding values:

def quote_backslach(line):
    result = ''
    find = '"'
    while find:
        start,find,line = line.partition(r'\"')
        result += start.replace('"',r'\"')+find
    return result

def toPHP(var, t):
    return ((r'%s .= "%s\n";' %
            (var, quote_backslach(line)))
           for line in t.split('\n') if line) ## if eliminates empty lines

print '\n'.join(toPHP("$txt",'''
<a href="test.php">some link</a>
<h1 class="small">Something</h1>
'''))
ultimatebuster 14 Posting Whiz in Training

isn't list comprehension the same as putting for and if statements inside an array (list/tuple)

TrustyTony 888 pyMod Team Colleague Featured Poster

So I thought myself one time, but test:

(i for i in range(10))

in command line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.