get values from an external page? - php

this code is in an external url: www.example.com.
</head><body><div id="cotizaciones"><h1>Cotizaciones</h1><table cellpadding="3" cellspacing="0" class="tablamonedas">
<tr style="height:19px"><td class="1"><img src="../mvd/usa.png" width="24" height="24" /></td>
<td class="2">19.50</td>
<td class="3">20.20</td>
<td class="4"><img src="../mvd/Bra.png" width="24" height="24" /></td>
<td class="5">9.00</td>
<td class="6">10.50</td>
</tr><tr style="height:16px" valign="bottom"><td class="15"><img src="../mvd/Arg.png" width="24" height="24" /></td>
<td class="2">2.70</td>
<td class="3">3.70</td>
<td class="4"><img src="../mvd/Eur.png" width="24" height="24" /></td>
<td class="5">24.40</td>
<td class="6">26.10</td>
</tr></table>
i want to get the values of the td, any suggestions? php,jquery etc.

You won't be able to do this with javascript, due to security restrictions that only allow you to load data from your own site.
You will have to pull the content with php (using something as simple as file_get_contents) and then parse it.
For the parsing, take a read through this comprehensive post:
How do you parse and process HTML/XML in PHP?
DOM is likely going to be your best bet.
Try playing around with this:
$html = file_get_contents('/path/to/remote/page/');
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('td') as $node) {
echo "Full TD html: " . $dom->saveHtml($node) . "\n";
echo "TD contents: " . $node->nodeValue . "\n\n";
}

Its not possible to do with jquery, however you can easily do it with PHP.
Use file_get_contents to read entire source code of the page into a string.
Parse, tokenise the string that contains the entire page source in order to grab all the td value.
<?php
$srccode = file_get_contents('http://www.example.com/');
/*$src is a string that contains source code of web-page http://www.example.com/
/*Now only thing you have to do is write a function say "parser" that tokenise or parse the string in order to grab all the td value*/
$output=parser($srccode);
echo $output;
?>
You have to be very careful while parsing the string to get desired output.For parsing you can either use regular expression or create your own look up table.You can use a HTML DOM parser written in PHP5 that let you manipulate HTML in a very easy way.A lot of such free parsers are available.

Related

How to send HTML (<table>) code through $_GET variable

EDIT: I solved my problem in total differnt way, thanks to those who respond anyways! helped a lot!
I need to send a table on HTML through a get variable.
The code is:
<html>
<head>
<meta charset="utf-8" />
<title>Itinerario</title>
<link rel="stylesheet" type="text/css" href="itine.css"/>
</head>
<body bgcolor="#FFC334" link="black" vlink="black" alink="white">
<?php
$html='
<font face="arial">
<center>
<table bgcolor="#F3F3F3" style="border:2px solid black;" cellpadding="10" cellspacing="10">
<tr>
<td></td>
<td>CELL 1</td>
<td>CELL 2</td>
</tr>
</table>
</center>
</font>
';
echo $html;
echo 'LINK ME';
?>
</body>
</html>
The other part its just a $_get:
<?php
$variable = $_GET['itine'];
?>
If I replace the $html in the URL for text it works fine but adding table structure sends nothing (no error), only blank.
Any ideas?
You wouldn't be able to send such complex HTML via GET, especially unescaped.
If you must pass HTML from page to page, you could base64_encode() the HTML, and probably gzcompress() it too. This would help prevent hitting the character limit for GET requests, but wouldn't eliminate the problem for very large tables.
I did once have to do something similar, which required passing a lot of data into GET variables. I had to create a couple of functions to make them GET friendly though:
function shrink($str) {
$str=strtr(base64_encode(addslashes(gzcompress($str,9))), '+/=', '-_,');
return $str;
}
function unshrink($str) {
$str = gzuncompress(stripslashes(base64_decode(strtr($str, '-_,', '+/='))));
return $str;
}
The shrink() function there gzips the string at compression level 9, and removes any characters from the encoded output that could cause issues for GET requests.
unshrink() does the opposite.
If you were to include those functions, you could do something like this in your example:
$html='
<font face="arial">
<center>
<table bgcolor="#F3F3F3" style="border:2px solid black;" cellpadding="10" cellspacing="10">
<tr>
<td></td>
<td>CELL 1</td>
<td>CELL 2</td>
</tr>
</table>
</center>
</font>
';
echo $html;
echo 'LINK ME';
Then to de-compress at the other end:
echo unshrink($_GET['itine']);
This was my first actual post here, so I hope it offers some help!
urlencode(), and no need to decode them, because when they are assigned to $_GET or $_POST they should already have been decoded.
The first problem is that you have a double quote in the HTML you want to send, this closes off the double quote of your a href.
Secondly, you might bump in the limitation of GET requests, theoretically they can only be 256 characters long.
Lastly, I would propose to you to urlencode/decode the data you try to send trough the url:
Encode:
echo 'LINK ME';
Decode:
<?php
$variable = urldecode($_GET['itine']);
?>
Well since you have some limitations about string length on $_GET, it's preferable not to do this. If you explain better what you need, maybe we can provide you another solution.

Getting PHP str_replace to work with Joomla

As you may know, Joomla components enable you to override their output by copying their template files into your site template. Joomla components generally use helper files which cannot be overridden.
I have a helper.php file that includes the string:
$specific_fields_text = '<tr><td class="key">'.$specific_field_title.': </td><td class="kr_sidecol_subaddress">'.$specific_fields[$i]->text.' '.$specific_fields[$i]->description.'</td></tr>';
In my template override is the code:
<table border="0" cellpadding="2" cellspacing="0">
<?php echo koparentHTML::getHTMLSpecificFields($this->specific_fields); ?>
</table>
The output is as follows:
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td class="key">title</td>
<td class="kr_sidecol_subaddress">value</td>
</tr>
<tr>
<td class="key">title</td>
<td class="kr_sidecol_subaddress">value</td>
</tr>
//.....etc......//
</table>
Basically I want to get rid of the table and turn it into a definition list but I cannot modify the helper.php file. I am thinking that the answer is to do with str_replace
I have tried using:
<dl>
<?php
$spec_fields = koparentHTML::getHTMLSpecificFields($this->specific_fields);
$spec_fields_dl = str_replace("<tr><td class='key'>'.$specific_field_title.': </td><td class='kr_sidecol_subaddress'>'.$specific_fields[$i]->text.' '.$specific_fields[$i]->description.'</td></tr>'", "<dt class='key'>'.$specific_field_title.': </dt><dd class='kr_sidecol_subaddress'>'.$specific_fields[$i]->text.' '.$specific_fields[$i]->description.'</dd>'", $spec_fields);
echo $spec_fields_dl;
?>
</dl>
This returns all of the text but with no html tags (no tr, td, dt, etc).
You can easily parse table data with PHP, like in this example:
$doc = new DOMDocument();
$doc->loadHTML(koparentHTML::getHTMLSpecificFields($this->specific_fields));
$rows = $doc->getElementsByTagName('tr');
$data = array();
for ($i = 0; $i < $rows->length; $i++) {
$cols = $rows->item($i)->getElementsbyTagName("td");
$data[$cols->item(0)->nodeValue] = $data[$cols->item(1)->nodeValue];
}
var_dump $data;
This should convert your table into assoc array ('title' => 'value').
I hope it helps.
I have figured this out. For some reason the PHP bits such as '.$specific_field_title.' where stopping the str_replace from working. To get around this I just searched for the HTML elements and put them in an array like so:
echo str_replace(array('<tr><td class="key">', '</td><td class="kr_sidecol_subaddress">', '</td></tr>'),
array('<dt class="key">', '</dt><dd class="kr_sidecol_subaddress">', '</dd>'),
koparentHTML::getHTMLSpecificFields($this->specific_fields));
And now this works perfectly. Thank you to everyone who contributed.

Correct syntax using JS 'onclick' functions inside PHP echo statements AND with embedded XML fetching

I am likely to get b'*ch slapped because I haven't searched the forum enough before posting, but I really think I searched all relevant posts already, many seem not specifically covering the question I have, the others fly right over my beginner's head ( as I am new to PHP & js ). That being said...
I have built a PHP code to fetch data from an XML file using the $xml=simplexml_load_file();
No worries there, however one of the needed data 'entries' or 'fields' needs to exist within an onclick and/or an onmouseup javascript function.
The code is as follows:
<?php
$xml=simplexml_load_file('prod_test_feed_sameday.xml');
$max = 8;
$i = 1;
foreach($xml->product as $feed){
if ($i <= $max){
echo "<table id='{$feed->position}' class='prod_container'>
<td class='hidden_mask' id='{$feed->position}'>
</td>
<td class='hidden_image' id='{$feed->position}'><span style='background:url({$feed->prod_image_large}) no-repeat center;'/></span><div><a onmouseup='$('.hidden_image#{$feed->position}').slideToggle('slow');' onclick='$('.hidden_mask#{$feed->position}').hide();'><b>CLOSE</b></a></div>
</td>
<tr>
<td class='prod_image' id='{$feed->position}'>
<span style='background:url({$feed->prod_image_small}) no-repeat center; background-size:contain;'/></span>
</td>
<td rowspan='1' class='info_toggle' id='{$feed->position}'><a onmouseup='$('.hidden_image#{$feed->position}').slideToggle('slow');' onclick='$('.hidden_mask#{$feed->position}').show();><img src='images/zoom_02.png' title='See a larger image of these flowers' /></a>
</td>
</tr>
<tr>
<td colspan='2' class='prod_name' id='{$feed->position}'>{$feed->prod_name}
</td>
</tr>
<tr>
<td colspan='2' class='prod_price' id='{$feed->position}'><span id='{$feed->position}'>from: £{$feed->price}</span><a href='{$feed->prod_link}' target='_blank'><span class='buy_button'> Buy it now! </span></a></td>
</tr>
</table>";
$i++;
}
}
?>
The data and the CSS all work perfectly. There is a href link towards the end of the code, which also works perfectly.
I am racking my brain trying to find the error in my syntax within the onlick function.
I have tried all manners of backslashing, using trial and error, for exampel:
onclick='$(\'.hidden_mask#{$feed->position}\').hide();' or
onclick='\'$('.hidden_mask#{$feed->position}').hide();\'' or
onclick=\''$(\'.hidden_mask#{$feed->position}\').hide();\'' or even
onclick=\''$(\\'.hidden_mask#{$feed->position}\\').hide();\'' <--Freddy Krugar 'slashing' example
At any rate I am at a loss.
Try with double quotes and escape them:
echo " ...
onclick=\"$('.hidden_mask#{$feed->position}').hide();\"
...";
Or
echo " ...
onclick='$(\".hidden_mask#{$feed->position}\").hide();'
...";
DEMO
This way you do the escaping in the PHP only, without needing the Freddy Krugar escaping for the DOM parser.

How to get data between <td> elements with Regex and Php

How can I get the "85 mph" from this html code with PHP + Regex ?
I couldn't come up with right regex
This is the code
http://pastebin.com/ffRH9K9Q
<td align="left">Los Angeles</td>
</tr>
<tr>
<td align="left">Wind Speed:</td>
<td align="left">85 mph</td>
</tr>
<tr>
<td align="left">Snow Load:</td>
<td align="left">0 psf</td>
(simplified example)
You've heard already about not using regex for the job, so I won't talk about that.
Let's try something here. Perhaps not the ideal solution, but could work for you.
<?php
$data = 'your table';
preg_match ('|<td align="left">(.*)mph</td>|Usi', $data, $result);
print_r($result); // Your result shoud be in here
You could need some trimming or taking whitespaces into account in the regex.
The first comment that links to the post about NOT PARSING HTML WITH REGEX is important. That said, try something like DOMDocument::loadHTML instead. That should get you started traversing the DOM with PHP.
To expand on DorkRawk's suggestion (in the hope of providing a relatively succinct answer that isn't overwhelming for a beginner), try this:
<?php
$yourhtml = '<td align="left">Los Angeles</td>
</tr>
<tr>
<td align="left">Wind Speed:</td>
<td align="left">85 mph</td>
</tr>
<tr>
<td align="left">Snow Load:</td>
<td align="left">0 psf</td>';
$dom = new DOMDocument();
$dom->loadHTML($yourhtml);
$xpath = new DOMXPath($dom);
$matches = $xpath->query('//td[.="Wind Speed:"]/following-sibling::td');
foreach($matches as $match) {
echo $match->nodeValue."\n\n";
}

How to parse XML/HTML server's reponse?

my first time here.
I got these lines as a response from the server and saved them in a file. They look like XML, right? My task is to read the content of those td tags and put them into other structured file(Excel). The problem is I dont know how to do that.
At the moment, I think I will strip the first and last line of the file then parse them into XML. But do you know other ways ? Thanks.
<CallbackContent><![CDATA[
<table cellspacing="0" border="0" cellpadding="0" width="100%">
<tr class="rowcolor2">
<td align="left" style="padding:5px;">22/02/2010</td>
<td align="right" style="padding:5px;">510,02</td>
</tr>
</table>
]]></CallbackContent>
Btw, I'm using PHP.
Use an XML parser such as SimpleXML. It will allow you to extract the CDATA safely.
Then if the HTML is XML-compliant (in other words, it's XHTML) you can use SimpleXML to extract data from it. For example:
$xml='<CallbackContent><![CDATA[
<table cellspacing="0" border="0" cellpadding="0" width="100%">
<tr class="rowcolor2">
<td align="left" style="padding:5px;">22/02/2010</td>
<td align="right" style="padding:5px;">510,02</td>
</tr>
</table>
]]></CallbackContent>';
$CallbackContent = simplexml_load_string($xml);
$html = (string) $CallbackContent;
// if XHTML
$table = simplexml_load_string($html);
// otherwise, use
$dom = new DOMDocument;
$dom->loadHTML($html);
$table = simplexml_import_dom($dom)->body->table;
foreach ($table->tr as $tr)
{
echo 'tr class=', $tr['class'], "\n";
foreach ($tr->td as $td)
{
echo 'td align=', $td['align'], ' - value: ', (string) $td, "\n";
}
}
You cannot read the table with an XML parser, because it is pushed out as a CDATA block, which equivocates to a string literal.
First, read the whole thing using a XML parser so that you can pull out the contents of the CDATA section. Then take that and stuff it through an HTML parser.

Categories