What is the fastest way to convert html table to php array? - php

are there build in functions in latest versions of php specially designed to aid in this task ?

Use a DOM parser like SimpleXML to split the HTML code into nodes, and walk through the nodes to build the array.
For broken/invalid HTML, SimpleHTMLDOM is more lenient (but it's not built in).

String replace and explode would work if the HTML code is clean and always the same, as soon as you have new attributes it will brake.
So only dependable solution would be using regular expressions or XML/HTML parser.
Check http://php.net/manual/en/book.dom.php

An alternative to using a native DOM parser could be using YQL. This way you dont have to do the actual parsing yourself. The YQL Web Service enables applications to query, filter, and combine data from different sources across the Internet.
For instance, to grab the HTML table with the class example given at
http://www.w3schools.com/html/html_tables.asp
you can do
$yql = 'http://tinyurl.com/yql-table-grab';
$yql = json_decode(file_get_contents($yql));
print_r( $yql->query->results );
I've deliberated shortened the URL so it does not mess up the answer. $yql actually links to the YQL API, adds some options and contains the query:
select * from html
where xpath="//table[#class='example']"
and url="http://www.w3schools.com/html/html_tables.asp"
YQL can return JSON and XML. I've made it return JSON and decoded this then, which then results in a nested structure of stdClass objects and Arrays (so it's not all arrays). You have to see if that fits your needs.
You try out the interactive YQL console to see how it works.

i dont know if this is the faster , but you can check this class (using preg_replace)
http://wonshik.com/snippet/Convert-HTML-Table-into-a-PHP-Array

If you want to convert the html-description of a table, here's how I would do it:
remove all closing tags (</...>) ( http://php.net/manual/de/function.str-replace.php)
split string at opening tags (<...>) using a regular expression ( http://php.net/manual/en/function.split.php)
You have to work out the details on your own, since I do not know if you want to handle different lines as subarrays or you want to merge all lines into one big array or something else.

you could use the explode-function to turn the table cols and rows into arrays.
see: php explode

Related

Search through multiple hosted XML files for a string

I'm working on a website that uses a lot of XML-files as data (150 in total and probably growing). Each page is an XML-file.
What I'm looking for is a way to look for a string through the XML-files. I'm not sure what programming language to use for this XML search engine.
I'm familiar with PHP, JavaScript, JQuery. So I'd prefer using those languages.
Thanks a bunch!
UPDATE: I'm looking for a solution that works quickly.
Ideally, the function returns the tagname that contains the searchstring.
If, for instance, the XML is as follows:
<article-1>This is a great story.</article-1>
If one would search for 'story', it would return 'article-1'.
I'm not quite sure on how to do this with a regular expression.
PHP can do this. Here's an example:
foreach(glob("{foldera/*.xml,folderb/*.xml}",GLOB_BRACE) as $filename) {
$xml = simplexml_load_file($filename);
//use regular expressions to find your string
}
You simply iterate through each file on your server using glob() with a foreach loop.
Sounds like a problem that could be solved with grep and regular expressions. Without knowing what string you're looking for it's not possible to say exactly what you should do, but reading some documentation on grep should get you started down the right path.

Dealing with XML in PHP

I'm currently working a project that has me working with XML a lot. I have to take an XML response and decrypt each text node and then do various tasks with the data. The problem I'm having is taking the response and processing each text node. Originally I was using the XMLToArray library, and that worked fine I would change the XML into an array and then loop through the array and decrypt the values. However some of the XML response I'm dealing with have repeated tags and the XMLToArray library will only return the last values.
Is there a good way that I can take an XML response and process all the text nodes and easily putting the values into an array that has a similar structure to the response?
Thanks in advance.
I would use SimpleXML.
Here's a small example of using it. It loads and parses XML from http://www.w3schools.com/xml/plant_catalog.xml and then outputs values of "COMMON" and "PRICE" tags of each "PLANT" tag.
$xml = simplexml_load_file('http://www.w3schools.com/xml/plant_catalog.xml');
foreach ( $xml->PLANT as $plantNode ) {
echo $plantNode->COMMON, ' - ', $plantNode->PRICE, "\n";
}
If you have any problems with adapting it to your needs, just give an example of your XML so that we can help with it.
All those XML to array libraries are a remain of the times where PHP 4 would force you to write your own XML parser almost from scratch. In recent PHP versions you have a good set of XML libraries that do the hard job. I particularly recommend SimpleXML (for small files) and XMLReader (for large files). If you still find them complicate, you can try phpQuery.
You might want to give SimpleXML a try. Plus it comes by default in php so you dont need to install
Check out SimpleXML, it may offer a bit more for what you are looking for.

Is it better to use pure DOM methods or string concatenation to generate a very dynamic xml file?

I basically have to query the database to grab all the active properties, then grab content under each property for sections such as accommodations/experiences, and based on that generate basically a site map.
I'm wondering if I should go with using purely DOM methods ( would have me doing a hundred or so createElements, inside of loops, appendChild, etc ) or just do a giant string concatenation and validate that then render it as xml?
Personally, I always try to use the DOM methods for XML generation. The reason is simple, it performs all the necessary escaping and entity generation for you.
$xmlBlock = '<foo>';
$xmlBlock .= '<bar>'.htmlspecialchars('baz', ENT_NOQUOTES, 'utf-8', false).'</bar>';
$xmlBlock .= '</foo>';
Compared to:
$node = $dom->createElement('foo');
$node->appendChild($dom->createElement('bar', 'baz'));
But then again, that's just my personal preference...
I would generate it with strings, in most cases.
$myXml = "<?xml ...... ";
$myXml .= "<rootNode>";
$myXml .= "<child>";
etc..
Performance-wise, string concatenation then doing a double-pass on the string is at a disadvantage. XML validation in the case of DOM methods is done for you automatically.
If you're concerned about performance, use output buffering to build the XML content. Also, build or find a trivial library that maintains a tag stack, does XML escaping, etc, so that you can guarantee well-formed output. That way, you can skip the validation pass unless you really need to verify conformance to a schema or DTD.
I don't know of anything in PHP, but the Android XmlSerializer is a good model of the minimum API you need to produce guaranteed-well-formed XML without building a DOM in memory as part of the process. The code involved isn't complicated and can be built and tested separately from any applications that use it.

Get a single element with PHP and XPath

Lots of tutorials around the net but none of them can explain me this:
How do I select a single element (in a table, for example), having its absolute XPath?
Example:
I have this:
/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[4]/td[5]/span
What's that PHP function to get the text of that element?!
Really I could not find an answer. Found lots of guides and hints to get all the elements of the table, all the buttons of a form, etc, but not what I need.
Thank you.
$xml = simplexml_load_string($html_content_string);
$arr = $xml->xpath("//body/table/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[4]/td[5]/span");
var_dump($arr);
Load you HTML document into a DOM object then make a DOMXPath object from it and let it evaluate your query string.
It's all described in detail here: http://php.net/manual/en/book.dom.php

Using PHP PCRE to fetch div content

I'm trying to fetch data from a div (based on his id), using PHP's PCRE. The goal is to fetch div's contents based on his id, and using recursivity / depth to get everything inside it. The main problem here is to get other divs inside the "main div", because regex would stop once it gets the next </div> it finds after the initial <div id="test">.
I've tryed so many different approaches to the subject, and none of it worked. The best solution, in my oppinion, is to use the R parameter (Recursion), but never got it to work properly.
Any Ideais?
Thanks in advance :D
You'd be much better off using some form of DOM parser - regex really isn't suited to this problem. If all you want is basic HTML dom parsing, something like simplehtmldom would be right up your alley. It's trivial to install (just include a single PHP file) and trivial to use (2-3 lines will do what you need).
include('simple-html-dom.php');
$dom = str_get_html($bunchofhtmlcode);
$testdiv = $dom->find('div#test',0); // 0 for the first occurrence
$testdiv_contents = $testdiv->innertext;

Categories