views:

989

answers:

3

I have a PHP script that does the following:

  • Uses file_get_contents() to get content of html file
  • Echos a JSON object

The issue is that the value obtained from file_get_contents is multi line. It needs to be all on one line in order to be in correct JSON format.

For example

PHP File:

$some_json_value = file_get_contents("some_html_doc.html");

echo "{";
echo "\"foo\":\"$some_json_value\"";
echo "}";

The resulting html document looks like:

{
foo: "<p>Lorem ipsum dolor 
sit amet, consectetur 
adipiscing elit.</p>"
}

My goal is to get the resulting html document to look like this (value is one line, not three)

{
foo: "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>"
}

How can this be done. I realize that the content will be one line if the original html doc is one line; however, I'm trying to avoid that solution.

Update

The question was answered correctly. Here is the complete, working code:

$some_json_value = file_get_contents("some_html_doc.html");
$some_json_value = json_encode($some_json_value); // this line is the solution

echo "{";
echo "\"foo\":\"$some_json_value\"";
echo "}";
A: 

You can replace all occurrences of \n and \r with "". Check out preg_replace.

Omega
I'm not trying to remove \n and \r
\n is a newline... As your subject states. You can still apply the same principles with call to preg_replace.
Omega
+1  A: 

Do a simple replace?

$content = str_replace(
    array("\r\n", "\n", "\r"), 
    '',
    file_get_contents('some_html_doc.html')
);

But a better idea would be to do a json_encode() right away;

$content = json_encode(file_get_contents('some_html_doc.html'));
Björn
+4  A: 

There are characters other than line-breaks which will cause you problems (double quotes and backslashes for example) and so rather than just strip out line-breaks, it would be better to encode your JSON properly. For PHP >= 5.2 there's the built-in json_encode function and there are libraries available for older versions of PHP (see e.g., http://abeautifulsite.net/notebook/71)

D. Evans
Best answer by far. +1
ceejayoz
That worked! I added your solution to my original question.
You could also just do this: echo json_encode(array('foo' => $some_json_value));
D. Evans
Thanks. It solved my problem when trying to keep some filled-with-tags' stuff in JS vars. +1
Alfabravo