Cannot convert mySQL database entries text '\n' to '<br>'in Angular? [duplicate] - php

This question already has answers here:
Preserve line breaks in mysqli fetch_assoc( ) PHP
(2 answers)
Closed 2 years ago.
I can read data to my angular app from the database but I am just given the static \n in my text instead of a new line. I am aware I am supposed to convert all \n occurrences to <br /> but I am failing to do this, even when using echo nl2br;
//extract from my php file
if($result = mysqli_query($con, $sql))
{
$animals = [];
$cr = 0;
while($row = mysqli_fetch_assoc($result))
{
$animals[$cr]['animal'] = $row['animal'];
$animals[$cr]['t1'] = $row['title1'];
$animals[$cr]['p1'] = $row['paragraph1'];
$cr++;
}
echo nl2br($animals);
echo json_encode($animals);
Below is my angular file
//extract from my animals.component.html file
<div class="container" *ngFor="let animal of this.animals">
{{animal.t1}}
{{animal.p1}}
{{animal.t2}}
</div>
However, my output on the webpage (coming from animal.t1) is just the same text as the database entry:
Animals \n are \n fun \n .
I have tried numerous different things and just cannot seem to convert the \n's to <br>. Has anyone got any advice on this?

nl2br takes a string not an array. If you select the columns in the query it is much easier. Just map the row array:
// SELECT animal, t1, p1 FROM table WHERE .....
while($row = mysqli_fetch_assoc($result))
{
$animals[] = array_map('nl2br', $row);
}
echo json_encode($animals);
If Angular is converting HTML to entities then you may want to look here Using HTML Entities within Angular strings

Use nl2br:
$animals[$cr]['t1'] = nl2br($row['title1']);

Related

How to echo multiple items from a single column on new line in PHP

I have two columns in my database that contain values entered from multiple select boxes. I used
$skills = join($_POST['skillSelect'],',');
$languages = join($_POST['languageSelect'],',');
to format them in the database. Now I want to display them to the user on a different page. They do display, but I want each on different lines. For example, let's say the user entered 'Java, PHP, JavaScript' as their language values. I want them to display as:
<p>Java</p>
<p>PHP</p>
<p>JavaScript</p>
However, they're just displaying as
Java, PHP, JavaScript
Here is my attempt using a foreach loop and explode:
<?php
$languages_explode = explode(PHP_EOL, $_SESSION['languages']);
foreach($languages_explode as $language) {
echo $language;
}
?>
I also tried:
echo "<p>".$language."</p>";
I thought the PHP_EOL delimiter would format it correctly, but I was wrong. How can I display each item on a new line, preferably within a paragraph tag? Thanks!
change this line
$languages_explode = explode(PHP_EOL, $_SESSION['languages']);
to
$languages_explode = explode(",", $_SESSION['languages']);
and then do
echo "<p>".$language."</p>";
try like this
your code from db is
Java, PHP, JavaScript
explode this to convert as array
$mystring = "Java, PHP, JavaScript";
$myArray = explode(',',$mystring);
//print_r($myArray);
foreach($myArray as $row)
{
echo "<p>".$row."</p><br>";
}

Json response with php

I am trying to get JSON response using PHP. I want to have Json array not the HTML tags. But the output shows HTML tags as well.I want to remove this HTML output! PHP code is as follows: I don't know how to do this ? Please help.
Thanks in advance :)
<?php
function getFixture(){
$db = new DbConnect();
// array for json response of full fixture
$response = array();
$response["fixture"] = array();
$result = mysql_query("SELECT * FROM fixture"); // Select all rows from fixture table
while($row = mysql_fetch_array($result)){
$tmp = array(); // temporary array to create single match information
$tmp["matchId"] = $row["matchId"];
$tmp["teamA"] = $row["teamA"];
$tmp["teamB"] = $row["teamB"];
array_push($response["fixture"], $tmp);
}
header('Content-Type: application/json');
echo json_encode($response);
}
getFixture();
?>
It's difficult to tell without seeing what your output is, but there is nothing in your code which would add HTML to your response.
It sounds like the HTML is in the database, so you're getting the data as expected, and your browser is the displaying whatever html elements might be there.
You could ensure none of the rows from the database have HTML in them by using strip_tags as follows:
$tmp["teamA"] = strip_tags($row["teamA"]);
Do this for all rows which may contain html.
Sorry if this is not formatted right, I'm new to StackOverflow!
http://php.net/strip-tags

How can I extract data from an HTML table in PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to parse and process HTML with PHP?
Let's say I want to extract a certain number/text from a table from here: http://www.fifa.com/associations/association=chn/ranking/gender=m/index.html
I want to get the first number on the right table td under FIFA Ranking position. That would be 88 right now. Upon inspection, it is <td class="c">88</td>.
How would I use PHP to extract the info from said webpage?
edit: I am told JQuery/JavaScript it is for this... better suited
This could probably be prettier, but it'd go something like:
<?php
$page = file_get_contents("http://www.fifa.com/associations/association=chn/ranking/gender=m/index.html");
preg_match('/<td class="c">[0-9]*</td>/',$page,$matches);
foreach($matches as $match){
echo str_replace(array( "/<td class=\"c\">", "</td>"), "", $match);
}
?>
I've never done anything like this before with PHP, so it may not work.
If you can work your magic after page load, you can use JavaScript/JQuery
<script type='text/javascript'>
var arr = [];
jQuery('table td.c').each(
arr[] = jQuery(this).html();
);
return arr;
</script>
Also, sorry for deleting my comment. You weren't specific as to what needed to be done, so I initially though jQuery would better fit your needs, but then I thought "Maybe you want to get the page content before an HTML page is loaded".
Try http://simplehtmldom.sourceforge.net/,
$html = file_get_html('http://www.google.com/');
echo $html->find('div.rankings', 0)->find('table', 0)->find('tr',0)->find('td.c',0)->plaintext;
This is untested, just looking at the source. I'm sure you could target it faster.
In fact,
echo $html->find('div.rankings', 0)->find('td.c',0)->plaintext;
should work.
Using DOMDocument, which should be pre-loaded with your PHP installation:
$dom = new DOMDocument();
$dom->loadHTML(file_get_contents("http://www.example.com/file.html"));
$xpath = new DOMXPath($dom);
$cell = $xpath->query("//td[#class='c']")->item(0);
if( $cell) {
$number = intval(trim($cell->textContent));
// do stuff
}

Converting MYSQL table data directly to an XML in PHP [duplicate]

This question already has answers here:
How to generate XML file dynamically using PHP?
(8 answers)
Closed 8 years ago.
I want to now if there is some inbuilt function that will create an XML directly from MYSQL result-set after executing SELECT query ?
I just wrote this and then thought id search to see if anyone else had written it. It looks simpler than the accepted answers tutorials. My $results comes from $result = mysql_query($query,$link);
$xmlDom = new DOMDocument();
$xmlDom->appendChild($xmlDom->createElement('results'));
$xmlRoot = $xmlDom->documentElement;
while ( $row = mysql_fetch_row($result) )
{
$xmlRowElementNode = $xmlDom->createElement('row');
$i=0;
for($i=0;$i<mysql_num_fields($result);$i++)
{
$xmlRowElement = $xmlDom->createElement(mysql_field_name($result,$i));
$xmlText = $xmlDom->createTextNode($row[$i]);
$xmlRowElement->appendChild($xmlText);
$xmlRowElementNode->appendChild($xmlRowElement);
}
$xmlRoot->appendChild($xmlRowElementNode);
}
header('Content-type: text/xml');
echo $xmlDom->saveXML();
This will procude XML in the form of
<results>
<row1>
<fieldname1>value</fieldname1>
<fieldname2>value</fieldname2>
<fieldname3>value</fieldname3>
<fieldname4...>value</fieldname4...>
</row1>
<row2>
<fieldname1>value</fieldname1>
<fieldname2>value</fieldname2>
<fieldname3>value</fieldname3>
<fieldname4...>value</fieldname4...>
</row2>
<row3...>
<fieldname1>value</fieldname1>
<fieldname2>value</fieldname2>
<fieldname3>value</fieldname3>
<fieldname4...>value</fieldname4...>
</row3...>
</results>
For any SELECT query.
There is no inbuilt function that will create XML directly from MYSQL result-set after executing SELECT query.
You have to write code for this
Some nice tutorials are this..
http://www.codediesel.com/php/converting-mysql-queries-to-xml/
http://www.mightywebdeveloper.com/coding/mysql-to-xml-php/
Generally your MySQL result will be returned as an array or an object, which you can then convert to XML or another format. You can use SimpleXML, which has been explained here: How to convert array to SimpleXML

PHP/HTML - Multiple page screen scrape, export to .txt with commas between dates and values

I am attempting to scrape the web page (see code) - as well as those pages going back in time (you can see the date '20110509' in the page itself) - for simple numerical strings. I can't seem to figure out through much trial and error (I'm new to programming) how to parse the specific data in the table that I want. I have been trying to use simple PHP/HTML without curl or other such things. Is this possible? I think my main issue is
using the delimiters that are necessary to get the data from the source code.
What I'd like is for the program to start at the very first page it can, say for example '20050101', and scan through each page till the current date, grabbing the specific data for example, the "latest close" (column), "closing arm" (row), and have that value for the corresponding date exported to a single .txt file, with the date being separated from the value with a comma. Each time the program is run, the date/value should be appended to the existing text file.
I am aware many lines of the code below are junk, it's part of my learning process.
<html>
<title>HTML with PHP</title>
<body>
<?php
$rawdata = file_get_contents('http://online.wsj.com/mdc/public/page/2_3021-tradingdiary2-20110509.html?mod=mdc_pastcalendar');
//$data = substr(' ', $data);
//$begindate = '20050101';
//$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
//if (preg_match(' <td class="text"> ' , $data , $content)) {
//$content = str_replace($newlines
echo $rawdata;
///file_put_contents( 'NYSETRIN.html' , $content , FILE_APPEND);
?>
<b>some more html</b>
<?php
?>
</body>
</html>
All right so let's do this. We're going to first load the data into an HTML parser, then create an XPath parser out of it. XPath will help us navigate around the HTML easily. So:
$date = "20110509";
$data = file_get_contents("http://online.wsj.com/mdc/public/page/2_3021-tradingdiary2-{$date}.html?mod=mdc_pastcalendar");
$doc = new DOMDocument();
#$doc->loadHTML($data);
$xpath = new DOMXpath($doc);
Now then we need to grab some data. First off let's get all the data tables. Looking at the source, these tables are indicated by a class of mdcTable:
$result = $xpath->query("//table[#class='mdcTable']");
echo "Tables found: {$result->length}\n";
So far:
$ php test.php
Tables found: 5
Okay so we have the tables. Now we need to get specific column. So let's use the latest close column you mentioned:
$result = $xpath->query("//table[#class='mdcTable']/*/td[contains(.,'Latest close')]");
foreach($result as $td) {
echo "Column contains: {$td->nodeValue}\n";
}
The result so far:
$ php test.php
Column contains: Latest close
Column contains: Latest close
Column contains: Latest close
... etc ...
Now we need the column index for getting the specific column for the specific row. We do this by counting all of the previous sibling elements, then adding one. This is because element index selectors are 1 indexed, not 0 indexed:
$result = $xpath->query("//table[#class='mdcTable']/*/td[contains(.,'Latest close')]");
$column_position = count($xpath->query('preceding::*', $result->item(0))) + 1;
echo "Position is: $column_position\n";
Result is:
$ php test.php
Position is: 2
Now we need to get our specific row:
$data_row = $xpath->query("//table[#class='mdcTable']/*/td[starts-with(.,'Closing Arms')]");
echo "Returned {$data_row->length} row(s)\n";
Here we use starts-with, since the row label has a utf-8 symbol in it. This makes it easier. Result so far:
$ php test.php
Returned 4 row(s)
Now we need to use the column index to get the data we want:
$data_row = $xpath->query("//table[#class='mdcTable']/*/td[starts-with(.,'Closing Arms')]/../*[$column_position]");
foreach($data_row as $row) {
echo "{$date},{$row->nodeValue}\n";
}
Result is:
$ php test.php
20110509,1.26
20110509,1.40
20110509,0.32
20110509,1.01
Which can now be written to a file. Now, we don't have the markets these apply to, so let's go ahead and grab those:
$headings = array();
$market_headings = $xpath->query("//table[#class='mdcTable']/*/td[#class='colhead'][1]");
foreach($market_headings as $market_heading) {
$headings[] = $market_heading->nodeValue;
}
Now we can use a counter to reference which market we're on:
$data_row = $xpath->query("//table[#class='mdcTable']/*/td[starts-with(.,'Closing Arms')]/../*[$column_position]");
$i = 0;
foreach($data_row as $row) {
echo "{$date},{$headings[$i]},{$row->nodeValue}\n";
$i++;
}
The output being:
$ php test.php
20110509,NYSE,1.26
20110509,Nasdaq,1.40
20110509,NYSE Amex,0.32
20110509,NYSE Arca,1.01
Now for your part:
This can be made into a function that takes a date
You'll need code to write out the file. Check out the filesystem functions for hints
This can be made extendible to use different columns and different rows
I'd recommend using the HTML Agility Pack, its a HTML parser which is very handy for finding particular content within a HTML document.

Categories