- Document Object Model
- Как вставить HTML, CSS и JS в PHP-код?
- Первый вариант вставки элементов в PHP-код
- Второй вариант вставки элементов в PHP-код
- How to Use HTML Inside PHP on the Same Page
- Html code inside PHP tags and using echo or print to show those HTML elements
- HTML вместе с PHP или HTML внутри PHP. О красоте кода.
- » rel=»bookmark» title=»»>ID, ‘name_rus’, true) ) : ?>ID, ‘name_rus’, true); ?>
- Читайте также
- Using PHP and HTML on the Same Page
- HTML in PHP
- My Example
- Use PRINT or ECHO
Document Object Model
// same as pq(‘anything’)->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery :: getDocument ();
?>
It uses DOM extension and XPath so it works only in PHP5.
If you want to use DOMDocument in your PHPUnit Tests drive on Symfony Controller (testing form)! Use like :
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use YourBundle\Controller\TextController;
class DefaultControllerTest extends WebTestCase
public function testIndex()
$client = static::createClient(array(), array());
$crawler = $client->request(‘GET’, ‘/text/add’);
$this->assertTrue($crawler->filter(«form»)->count() > 0, «Text form exist !»);
$domDocument = new \DOMDocument;
$domInput = $domDocument->createElement(‘input’);
$dom = $domDocument->appendChild($domInput);
$dom->setAttribute(‘slug’, ‘bloc’);
$formInput = new \Symfony\Component\DomCrawler\Field\InputFormField($domInput);
$form->set($formInput);
if ($client->getResponse()->isRedirect())
$crawler = $client->followRedirect(false);
>
// $this->assertTrue($client->getResponse()->isSuccessful());
//$this->assertEquals(200, $client->getResponse()->getStatusCode(),
// «Unexpected HTTP status code for GET /backoffice/login»);
When I tried to parse my XHTML Strict files with DOM extension, it couldn’t understand xhtml entities (like ©). I found post about it here (14-Jul-2005 09:05) which adviced to add resolveExternals = true, but it was very slow. There was some small note about xml catalogs but without any glue. Here it is:
XML catalogs is something like cache. Download all needed dtd’s to /etc/xml, edit file /etc/xml/catalog and add this line:
I hate DOM model !
so I wrote dom2array simple function (simple for use):
function dom2array($node) $res = array();
print $node->nodeType.’
‘;
if($node->nodeType == XML_TEXT_NODE) $res = $node->nodeValue;
>
else if($node->hasAttributes()) $attributes = $node->attributes;
if(!is_null($attributes)) $res[‘@attributes’] = array();
foreach ($attributes as $index=>$attr) $res[‘@attributes’][$attr->name] = $attr->value;
>
>
>
if($node->hasChildNodes()) $children = $node->childNodes;
for($i=0;$ilength;$i++) $child = $children->item($i);
$res[$child->nodeName] = dom2array($child);
>
>
>
return $res;
>
The project I’m currently working on uses XPaths to dynamically navigate through chunks of an XML file. I couldn’t find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function. Turns out it wasn’t as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans.
Hopefully it’ll save someone else the trouble of reinventing this wheel.
function getNodeXPath ( $node ) // REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0.
// Get the index for the current node by looping through the siblings.
$parentNode = $node -> parentNode ;
if( $parentNode != null ) $nodeIndex = 0 ;
do $testNode = $parentNode -> childNodes -> item ( $nodeIndex );
$nodeName = $testNode -> nodeName ;
$nodeIndex ++;
// PHP trickery! Here we create a counter based on the node
// name of the test node to use in the XPath.
if( !isset( $ $nodeName ) ) $ $nodeName = 1 ;
else $ $nodeName ++;
// Failsafe return value.
if( $nodeIndex > $parentNode -> childNodes -> length ) return( «/» );
> while( ! $node -> isSameNode ( $testNode ) );
// Recursively get the XPath for the parent.
return( getNodeXPath ( $parentNode ) . «/ < $node ->nodeName > [ ]» );
> else // Hit the root node! Note that the slash is added when
// building the XPath, so we return just an empty string.
return( «» );
>
>
?>
If you want to print the DOM XML file content, you can use the next code:
$doc = new DOMDocument();
$doc->load($xmlFileName);
echo «
» . $doc->documentURI;
$x = $doc->documentElement;
getNodeContent($x->childNodes, 0);
function getNodeContent($nodes, $level) foreach ($nodes AS $item) // print «
TIPO: » . $item->nodeType ;
printValues($item, $level);
if ($item->nodeType == 1) < //DOMElement
foreach ($item->attributes AS $itemAtt) printValues($itemAtt, $level+3);
>
if($item->childNodes || $item->childNodes->lenth > 0) getNodeContent($item->childNodes, $level+5);
>
>
>
>
function printValues($item, $level) if ($item->nodeType == 1) < //DOMElement
printLevel($level);
print $item->nodeName . »
«;
if ($level == 0) print «
«;
>
for($i=0; $i < $level; $i++) print "-";
>
>
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.
DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR
DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID
PHP 5.1 users are encouraged to use the new constants.
Как вставить HTML, CSS и JS в PHP-код?
Когда вы разрабатываете свой модуль, то иногда прибегаете к помощи верстки (HTML и CSS) и дополнительным скриптам.
Все это можно подключать отдельно – что-то в теле страницы, что-то в отдельных файлах. Но некоторые дополнения лучше вставлять непосредственно в сам PHP-файл.
Сегодня я покажу два варианта, как можно вставить HTML, CSS или JavaScript в код PHP.
Первый вариант вставки элементов в PHP-код
Я думаю, что если вы хоть немного знакомы с PHP, то знаете, что такое «echo» (тег, с помощью которого вы можете вывести сообщение на экран).
Вот с помощью него и можно вывести один из перечисленных ранее кодов. Пример:
"; echo $content; ?>
На что здесь стоит обратить внимание? Кавычки. Если вы используете внешние кавычки в виде » «, то внутренние кавычки элементов должны быть ‘ ‘ и наоборот, иначе вы получите ошибку. Если вы принципиально хотите использовать одинаковые и внешние, и внутренние кавычки, то во внутренних ставьте знак экранизации:
"; echo $content; ?>
В этом случае все будет работать корректно.
Второй вариант вставки элементов в PHP-код
Этот вариант мне нравится куда больше, чем первый. Здесь мы будем также использовать «echo», как и в предыдущем варианте, но добавим еще элемент «HTML»:
Сюда вы можете вставлять любой элемент, будь то HTML-код или же JavaScript. Кавычки здесь не играют роли (можете вставить любые), а по желанию можно внедрить переменные для вывода:
"; echo HTML; ?>
Весьма удобный способ для реализации ваших идей.
How to Use HTML Inside PHP on the Same Page
Here in this file as you can see that PHP code is being put inside html tags namely HTML tag and BODY tag and php code is written inside PHP delimiters (lines 4 and 7) $name=”your name”; is a variable that stores the string inside ” ” and here string stores in variable name is Your name $ is used to declare a variable in PHP. Right now this is the only thing I know about variables and how to declare them in PHP. I am planning to read more about it later and then I’ll record what I understand through the blog post. print $name; Here I have used Print to show the value stored in the variable $name .
print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.
There is more to this function I suppose and will study it in detail. I could also have used echo to obtain the same thing. In line 10 see that I have put PHP code inside the bold html tag ( ) which resulted in bold faced “your name” string. So this way you can put your PHP scripts inside any HTML tags. There are other alternative PHP delimiters you can use to tell server to distinguish between your php script and other webpage elements.
Although these alternative PHP delimiters can be used but I have read that these forms should be avoided and you in practice should use following PHP delimiter as used firstly inside HTML file
Html code inside PHP tags and using echo or print to show those HTML elements
We can use html tags inside PHP also as given below
" echo "" $name="your name"; print $name; echo "
" echo "" print $name; echo "" echo "" echo "