0

I have one line in php file like this:

<a class="hide-if-no-js" onclick="findPosts.open( 'media[]','<?php echo $post->ID ?>' ); return false;" href="#the-list">Attach</a>

I need to write this line as a string in a php function, I tried this:

$output .="<a class='hide-if-no-js' onclick='findPosts.open( 'media[]','$id' ); return false;' href='#the-list'>'$linktext'</a>";

Seems the quote around 'media[]' is wrong and made the html of this line messed up. Could anybody help correct me?

1
  • If you need to output this, why don't you output it directly outside the PHP script? Commented Jun 20, 2012 at 2:21

2 Answers 2

2
$output .= "<a class=\"hide-if-no-js\" onclick=\"findPosts.open( 'media[]','$id' ); return false;\" href=\"#the-list\">$linktext</a>";

Your javascript string use single quote, so the html attribute should use double quote.

Sign up to request clarification or add additional context in comments.

8 Comments

You could also use a HEREDOC or an output buffer to avoided having to use escaped quotes, although in this case either the attribute quotes or the embedded Javascript quotes would need to be reversed.
Also, are you saying HTML attributes are required by spec to use "?
As per the RFC, either double quotes or single quotes can be used for HTML attributes.
In XHTML. There's no indication that's the case here, and if you make a comment like that, it needs to be specific. That's how people get the idea it's required but can't remember why. And hey, y'know, I prefer double-quotes, but it's not factually correct by omission.
@Jenny - I meant you have two considerations for escaping quotes using double-quoted strings in your PHP; the others you only have one, but that case still exists in your html because you can't have the same quotes for attributes and within attribute values. So you would still have to reverse one set. Nothing to do with any JS function.
|
1

You can try:

$output .= '<a class="hide-if-no-js" onclick="findPosts.open( \'media[]\',\'' . $id . '\' ); return false;" href="#the-list">' . $linktext . '</a>';

OR

$output .= "<a class='hide-if-no-js' onclick='findPosts.open( \"media[]\", \"$id\" ); return false;' href='#the-list'>$linktext</a>";

4 Comments

Note there is a PHP variable in there that needs expansion using ".
@JaredFarrish, Note that the variables are concatened with the string, so it will be returned normally
The original, non-recorded response didn't have the concatenation. And then you edited it initially and fixed it. I'm not blind.
@JaredFarrish, Maybe i forgot, anyway, thanks for your comment!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.