Showing posts with label Xpath. Show all posts
Showing posts with label Xpath. Show all posts

14 February, 2011

How to get all hidden elements from a form using php

I always had problem getting all the hidden elements of a form when using cURL. So thought of making a function that extracts all the hidden elements from a form when passed as a string.
Here's the function

function getHidden($form) {
$hiddenElements="";
$doc=new DOMDocument();
$doc->loadHTML($form);
$xpath=new DOMXPath($doc);

//use xPATH for quering the hidden elements in a form passes as string $form
$qry="//input[@type='hidden']";
$xData=$xpath->query($qry);

//loop thru all the data
foreach($xData as $value) {
//typecast the name and values as string to avoid xml object
$eleName=(string) $value->getAttribute('name');
$eleValue=(string) $value->getAttribute('value');
$hiddenElements[$eleName]=$eleValue;
}
return $hiddenElements;
}

?>

And thats it. The above function can be useful while doing a cURL using php to get form fields. Hope this helps someone

16 May, 2010

Xpath in PHP

XPath allows you to retrieve any infromation from xml data. Working with xpath in php is quite simple in some sense
and quite complex in some sense. Some simple xpath queries are explained as a beginning for xpath using php.
Consider following XML file, saved as test.xml




Professinal PHP
Someone not me

One
Two


Beginning PHP
PHP with Ajax
PHP .NET



Now to load the xml file and perform XPath query


$doc = new DOMDocument();
//load the xml file
$doc->load("test.xml");

//create XPath
$newXpath = new DOMXPath($doc);
//get all the title tags from the loaded xml
$books = $newXpath->query("/books/book/title");
//show all the title values such as Professional PHP, Beginning PHP, PHP with Ajax and PHP .NET
foreach($books as $book) {
echo $book->nodeValue."
";
}

//now to get only the title that has certain attributes value such as isbn value in this case
//we do the following, following code shows title Beginning PHP
$onlyBook = $newXpath->query("/books/book[@isbn='1234']/title");

//to get title depending on some values, such as
//following code shows Professional PHP
$firstTitlte = $newXpath->query("/books/book/srcs[src='One' or src='Two']/../title");
?>