How can you hide html element with php? - php

if you do in php:
$dom = new DOMDocument();
$dom->loadHTML($pageUrl);
$dom->getElementById(eleId);
How can you hide the element. I know how you can do it with css and js. But I want to know it with php.

I’m going to assume that you’re trying to have the element initially hidden i.e. in existence, but not visible, upon the browser’s initial rendering and you already know that PHP can’t directly instruct the browser to hide elements.
Following your example, you could do:
$eleId = “div_to_hide”;
$dom = new DOMDocument();
$dom->loadHTML($pageUrl);
$target_elem = $dom->getElementById($eleId);
if ($target_elem) {
$target_elem-> setAttribute('style','display: none;');
}
Or you could create a “script” element containing JavaScript code to execute after the resource has totally downloaded to hide it at run-time.
Or you could create a “style” element in your DOMDocument object in which you’d put CSS content referencing the target element (by selector) to apply initial “display: none;” CSS.
Just other ideas, but the snippet above follows your paradigm.

Related

Load html content from ajax response

I am creating an application in opencart in which the controller returns output in json form. If i do $('.my-div').html(json['output']) then its working fine. But how can i filter particular div or table from that response and put only that filtered html in my div. I know about $('.my-div').load('index.php?route=mymodule/subpage' .my-div > * ); But it doesn't work as my controller is created to return output not to generate.
What my controller returns is
$json['output'] = $this->load->view('default/template/mymodule/mytemplate.tpl', $data);
Edit
What i am getting in response is
json['output'] = '<div>......</div><table class="myclass"></table>';
I want to load only myclass in my div. So how can i filter only myclass table from response.? I've tried filter but its giving me error.
Like Raghubendra said, it's better to only keep the html you need in the .tpl file, but if you can't do that for whatever reason, you can try to filter it on the server side using xPath [it's not the fastest way, but it's a clean way to get the result]. Here is how I think you can do it:
$output = $this->load->view('default/template/mymodule/mytemplate.tpl', $data);
$dom = new DOMDocument();
#$dom->loadHTML($output); // # is to suppress all warnings related to the fact that html is not a proper dom document
$xpath = new DOMXPath($dom);
$match = $xpath->query('//table[#class="myclass"]');
/* $match is not an array, it implements 'Traversable', you can't access your <table> node using $match[0],
you need a foreach that will only loop once if you have one <table class="myclass"> element */
foreach($match as $table) {
$json['output'] = $table->ownerDocument->saveHTML($table); // saveHTML allows you to get the output in an HTML string
}
N.B: Please note that you need to change this code in case you have multiple <table class="myclass">, I would recommend using iterator_to_array($match); to transform the node list to an array so you can access it using $match[0]... and avoid the foreach.
If you want only a part of the html in your div then why are you rendering the whole tpl file. Why don't you remove the html code that you don't want to use.
Suppose if your mytemplate.tpl has
<div>
---------
--------
</div>
<table class="myclass"></table>
<div>
---------
--------
</div>
Then why don't you only keep the table code are remove all the other code as you are not using it while rendering the tpl file.

Form to pull page elements using file_get_contents and getElementsByClassName in PHP

I'm attempting to create a page where I input a url and the PHP code uses that to pull page elements from another website to be displayed on my blog post. I haven't even made it as far as the form, right now I just need to understand how to get this code to work so that it displays the page elements within the div with the class "products-grid first odd".
<?php
$homepage = file_get_contents('website');
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$dochtml->getElementsByClassName('products-grid first odd');
echo ????
?>
The PHP DOMDocument object does not appear to have the method getElementsByClassName().
Instead, I think you would have to getElementsByTagName() and then loop through those DOMElements and getAttribute('class') on each and check until you find the right one.

manipulate html navigation with php dom

I need to add classes to the navigation HTML being output from a function in a custom CMS.
The only way I can get the output I need is to parse the HTML with PHP.
I am using PHP's DOM methods to look through the HTML and add a class to any <li> element that contains a child <ul> (top level navigation items).
So far it's working, but I have 2 questions:
Is there a more efficient way for me to go through this DOM data? It seems cumbersome to me, but that could just be my lack of experience.
In some cases, my <li> elements may already have a class, how can I add to the existing class attribute without destroying what may or may not already be there?
-
<?
$mcms_nav = getContent(
// call to cms that returns navigation html as a string
// ex. <ul id="pnav"><li>home</li>....</ul>
);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = FALSE;
$dom->loadHTML($mcms_nav);
$x = new DOMXPath($dom);
foreach($x->query('//ul/li/ul') as $node)
{
$parent = $node->parentNode;
$parent_attr = $dom->createAttribute('class');
$parent_attr->value = 'has-flyout';
$parent->appendChild($parent_attr);
$flyout_attr = $dom->createAttribute('class');
$flyout_attr->value = 'flyout';
$node->appendChild($flyout_attr);
}
$mcms_nav = $dom->getElementByID('pnav');
echo $dom->saveHTML($mcms_nav);
?>
Not really. You could take the XML class from the CakePHP framework, turn this into an array, manipulate the array, and turn it back. Not sure if that's an option in your case. http://book.cakephp.org/2.0/en/core-utility-libraries/xml.html
You can use dom->hasAttribute() and dom->getAttribute() to get the existing attribute contents if they exist.
Also, a new job wouldn't hurt ;)

How do I get the link element in a html page with PHP

First, I know that I can get the HTML of a webpage with:
file_get_contents($url);
What I am trying to do is get a specific link element in the page (found in the head).
e.g:
<link type="text/plain" rel="service" href="/service.txt" /> (the element could close with just >)
My question is: How can I get that specific element with the "rel" attribute equal to "service" so I can get the href?
My second question is: Should I also get the "base" element? Does it apply to the "link" element? I am trying to follow the standard.
Also, the html might have errors. I don't have control on how my users code there stuff.
Using PHP's DOMDocument, this should do it (untested):
$doc = new DOMDocument();
$doc->loadHTML($file);
$head = $doc->getElementsByTagName('head')->item(0);
$links = $head->getElementsByTagName("link");
foreach($links as $l) {
if($l->getAttribute("rel") == "service") {
echo $l->getAttribute("href");
}
}
You should get the Base element, but know how it works and its scope.
In truth, when I have to screen-scrape, I use phpquery. This is an older PHP port of jQuery... and what that may sound like something of a dumb concept, it is awesome for document traversal... and doesn't require well-formed XHTMl.
http://code.google.com/p/phpquery/
I'm working with Selenium under Java for Web-Application-Testing. It provides very nice features for document traversal using CSS-Selectors.
Have a look at How to use Selenium with PHP.
But this setup might be to complex for your needs if you only want to extract this one link.

How can I load an external page with PHP and replace content on that page?

I'm building a PHP app that allows a user to upload an ad and preview it on specific pages of a specific website. Right now, I'm doing it by taking screenshots of the webpage, removing the ads, and placing my own s. This seems pretty stupid.
What would be the best way to get the contents of a URL and replace code that appears between a certain on that page?
Load the page source into a DOMDocument object
Do a search and replace using XPath on the DOMDocument object
Example:
<?php
$dom = new DOMDocument();
$dom->strictErrorChecking = false;
$dom->loadHTMLFile("http://www.example.com");
$xpath = new DOMXPath($dom);
$logoImage = $xpath->query("//div[#id='header-logo']//a//img")->item(0);
$logoImage->setAttribute('src', 'http://www.google.com/images/logos/ps_logo2.png');
$logoLink = $xpath->query("//div[#id='header-logo']//a")->item(0);
$logoLink->setAttribute('href', 'http://www.google.com/');
echo $dom->saveHTML();
?>
The example loads the source of example.com and replaces the logo with google.com's logo and a link to google.
The code does not have any validation but should be pretty easy to modify for your needs :)
I am not sure about complete situation that how you would like to perform this action.
However on base of your question best way is to use Ajax.
Through Ajax pass detail of page you want to display and in php filter page as you want to display and return desired result.
And at the end of Ajax request display your result in particular location.
Even in JavaScript you can filter result as you like returned by Ajax request.

Categories