using simple xml to read parts of an html page returns warning's / notice of non-object, and need to fix this [duplicate] - mysqli

This question already has answers here:
PHP SimpleXML: How can I load an HTML file?
(4 answers)
Closed 9 years ago.
Okay so I've been working on this little script which is bascially scrapping a page from ted.com everything works as i want it to (meaning I can print out all values that I am interested in), The problem is for some reason i get these warning when running the scraper but am unsure as to why as the values the notice / warning occer on are printed out properly
PHP Warning: dom_import_simplexml() expects parameter 1 to be object, null given in /var/www/ted/import_ted.php on line 23
PHP Notice: Trying to get property of non-object in /var/www/ted/import_ted.php on line 23
PHP Notice: Undefined offset: 1 in /var/www/ted/import_ted.php on line 25
PHP Notice: Trying to get property of non-object in /var/www/ted/import_ted.php on line 27
and this is my actually php script (I've commented lines where warning's and Notice)
<?php
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$html = file_get_contents('http://www.ted.com/talks/quick-list?sort=date&order=desc');
$doc = new DOMDocument();
$doc->loadHTML($html);
$sxml = simplexml_import_dom($doc);
$rows = $sxml->xpath('//tr');
$description="not_available";
$ted_link="none";
$i=0;
//$stmt = $mysqli->prepare("INSERT INTO `ted` VALUES( ?, ?, ?, ?, ?, ?, ?)");
foreach($rows as $row) {
$video = Array();
$video['pub_date']= $row->td[0];
$video['event'] = $row->td[1];
$sec_temp = explode(":" , dom_import_simplexml($row->td[2])->textContent );//line23
$video['speaker'] = $sec_temp[0];
$video['title'] = $sec_temp[1]; //line 25
$video['duration'] = $row->td[3];
$video['link'] = $row->td[4]->a[2]['href']; //line27
print( "\n line Number: " . $i . "title: " . $video['title']);
print ("link: " .$video['link']);
if($i != 0){
// $stmt->bind_param("sssssss", $video['event'], $video['speaker'], $video['title'], $description, $ted_link, $video['link'], $description, $video['pub_date'] );
// $stmt->execute();
}
$i++;
}
// $stmt->close();
?>
Okay so Like I said Everything prints out what I am expecting including $video['title'] which generates an undefined offset for some reason. The problem is until I can make these variable "objects" I cannnot bind them as parameters to mysqli query. However I can't seem to figure out how to do this?
also incase relevent here is a snippet of a table row incase this is the problem (which I do not think it is )
<tr>
<td>Jun 2013</td>
<td>TEDGlobal 2013</td>
<td>Manalal-Sharif: A Saudi woman who dared to drive </td>
<td>14:16</td>
<td>Low | Regular | High</td>
</tr>
Note also I have tried using settype($var, "object") before binding with no luckeither (though reurned true)
Anyways any help with how I can get this to work would be greatly appreciated!

<?php
$html = file_get_contents('http://www.ted.com/talks/quick-list?sort=date&order=desc');
$doc = new DOMDocument();
$doc->loadHTML($html);
$sxml = simplexml_import_dom($doc);
$rows = $sxml->xpath('//tr');
/* print_r($rows);
die(); */
$description="not_available";
$ted_link="none";
$i=0;
//$stmt = $mysqli->prepare("INSERT INTO `ted` VALUES( ?, ?, ?, ?, ?, ?, ?)");
foreach($rows as $row) {
//first object is th not an td
if(isset($row->th))
{
echo $row->th[1]->a;
echo $row->th[2]->a;
echo $row->th[3]->a;
echo $row->th[4];
}else{
$video['pub_date']= $row->td[0];
$video['event'] = $row->td[1];
$sec_temp = explode(":" , $row->td[2]->a);//line23
$video['speaker'] = $sec_temp[0];
$video['title'] = $sec_temp[1]; //line 25
$video['duration'] = $row->td[3];
$video['link'] = $row->td[4]->a[2]['href']; //line27
print( "\n line Number: " . $i . "title: " . $video['title']);
print ("link: " .$video['link']);
if($i != 0){
// $stmt->bind_param("sssssss", $video['event'], $video['speaker'], $video['title'], $description, $ted_link, $video['link'], $description, $video['pub_date'] );
// $stmt->execute();
}
$i++;
}
}

Related

How correctly to use the snippet() function?

My first Sphinx app almost works!
I successfully save path,title,content as attributes in index!
But I decided go to SphinxQL PDO from AP:
I found snippets() example thanks to barryhunter again but don't see how use it.
This is my working code, except snippets():
$conn = new PDO('mysql:host=ununtu;port=9306;charset=utf8', '', '');
if(isset($_GET['query']) and strlen($_GET['query']) > 1)
{
$query = $_GET['query'];
$sql= "SELECT * FROM `test1` WHERE MATCH('$query')";
foreach ($conn->query($sql) as $info) {
//snippet. don't works
$docs = array();
foreach () {
$docs[] = "'".mysql_real_escape_string(strip_tags($info['content']))."'";
}
$result = mysql_query("CALL SNIPPETS((".implode(',',$docs)."),'test1','" . mysql_real_escape_string($query) . "')",$conn);
$reply = array();
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$reply[] = $row['snippet'];
}
// path, title out. works
$path = rawurlencode($info["path"]); $title = $info["title"];
$output = '<a href=' . $path . '>' . $title . '</a>'; $output = str_replace('%2F', '/', $output);
print( $output . "<br><br>");
}
}
I have got such structure from Sphinx index:
Array
(
[0] => Array
(
[id] => 244
[path] => DOC7000/zdorovie1.doc
[title] => zdorovie1.doc
[content] => Stuff content
I little bit confused with array of docs.
Also I don't see advice: "So its should be MUCH more efficient, to compile the documents and call buildExcepts just once.
But even more interesting, is as you sourcing the the text from a sphinx attribute, can use the SNIPPETS() sphinx function (in setSelect()!) in the main query. SO you dont have to receive the full text, just to send back to sphinx. ie sphinx will fetch the text from attribute internally. even more efficient!
"
Tell me please how I should change code for calling snippet() once for docs array, but output path (link), title for every doc.
Well because your data comes from sphinx, you can just use the SNIPPET() function (not CALL SNIPPETS()!)
$query = $conn->quote($_GET['query']);
$sql= "SELECT *,SNIPPET(content,$query) AS `snippet` FROM `test1` WHERE MATCH($query)";
foreach ($conn->query($sql) as $info) {
$path = rawurlencode($info["path"]); $title = $info["title"];
$output = '<a href=' . $path . '>' . $title . '</a>'; $output = str_replace('%2F', '/', $output);
print("$output<br>{$info['snippet']}<br><br>");
}
the highlighted text is right there in the main query, dont need to mess around with bundling the data back up to send to sphinx.
Also shows you should be escaping the raw query from user.
(the example you found does that, because the full text comes fom MySQL - not sphinx - so it has no option but to mess around sending data back and forth!)
Just for completeness, if REALLY want to use CALL SNIPPETS() would be something like
<?php
$query =$conn->quote($_GET['query']);
//make query request
$sql= "SELECT * FROM `test1` WHERE MATCH($query)";
$result = $conn->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
//build list of docs to send
$docs = array();
foreach ($rows as $info) {
$docs[] = $conn->quote(strip_tags($info['content']));
}
//make snippet reqest
$sql = "CALL SNIPPETS((".implode(',',$docs)."),'test1',$query)";
//decode reply
$reply = array();
foreach ($conn->query($sql) as $row) {
$reply[] = $row['snippet'];
}
//output results using $rows, and cross referencing with $reply
foreach ($rows as $idx => $info) {
// path, title out. works
$path = rawurlencode($info["path"]); $title = $info["title"];
$output = '<a href=' . $path . '>' . $title . '</a>'; $output = str_replace('%2F', '/', $output);
$snippet = $reply[$idx];
print("$output<br>$snippet<br><br>");
}
Shows putting the rows into an array, because need to lopp though the data TWICE. Once to 'bundle' up the docs array to send. Then again to acully display rules, when have $rows AND $reply both available.

pg_fetch_assoc returning 1 after values

I am beginner in PHP, i am working with session and pg functions. So i want to return user's first name and last name from database(basically user's details) and display it to different page using session. and it is returning using pg_fetch_assoc() but the problem is like it is showing 1 after every value like (firstname 1), (lastname 1). How can i fix it. is there any other way to return values from database and display it and also use these values as conditions.
Thanks
Below is my code:
$login = trim($_POST['login']);
$pass = trim($_POST['pass']);
$result = pg_execute($conn, "login_query", array($login, hash(HASH_ALGO, $pass)));
$records = pg_num_rows($result);
if($records == 1){
$_SESSION['user_id'] = $login;
$row = pg_fetch_assoc($result);
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
$_SESSION['last_access'] = $row['last_access'];
$_SESSION['user_type'] = $row['user_type'];
//$_SESSION['details'] = $row;
pg_execute($conn, "update_query", array($login));
/* $_SESSION['output'] = $output();*/
$_SESSION['output'] = "Welcome back " . pg_fetch_result($result,0,"first_name") . pg_fetch_result($result,0,"last_name").'</br>';
$_SESSION['output'] .= "Our records show that your </br>" . "email address is " . pg_fetch_result($result,0,"email_address") . "</br>";
$_SESSION['output'] .= "and you last accessed our system: " . pg_fetch_result($result,0,"last_access") . "</br>";
header('location: ./user-dashboard.php');
}
here is var_dump($row); value:
array(9) { ["user_id"]=> string(20) "jdoe " ["password"]=> string(32) "179ad45c6ce2cb97cf1029e212046e81" ["user_type"]=> string(2) "c " ["email_address"]=> string(256) "jdoe#gmail.com " ["first_name"]=> string(128) "John " ["last_name"]=> string(128) "Doe " ["birth_date"]=> string(10) "1998-02-05" ["enrol_date"]=> string(10) "2017-01-01" ["last_access"]=> string(10) "2017-10-18" }
database
pg_fetch_assoc returns values OK. you can see it in result of var_dump($row); - see the ["last_name"]=> string(128) "Doe " - it has extra space - yes, but not 1. So another bit of code adds 1 after $row["last_name"] value.
<h1 class="floating-box" ><?php echo print_r($_SESSION['first_name'],True); ?></h1>
<h1 class="floating-box" ><?php echo print_r($_SESSION['last_name']); ?></h1>
<h1 class="floating-box" ><?php echo print_r($_SESSION['last_access']); ?></h1>
Sorry, i forgot to add true in print_r() function. Thanks for your help. #Vao Tsun

Returning an array using PDO

I'm trying to use PDO using the following code, I want to select the array of values for the context_list, but it returns one record, any ideas where I'm going wrong?
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list = $row['area_easting'];
$northing_list = $row['area_northing'];
$context_list = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo $context_list;
A partial solution:
This worked:
$query = $conn->prepare("SELECT area_easting, area_northing, context_number FROM excavation.contexts");
$query->execute();
while($r = $query->fetch(PDO::FETCH_OBJ)){
echo $r->area_easting, '|';
echo $r->area_northing;
echo '<br/>';
}
But Now I need to make the $r->area_easting accessible to the session, but that's another question.
Your query may return several records (provided they actually exist in the table).
Your code loops through all the records (with the while loop) but the values ($easting_list, $northing_list and $context_list) are overwritten in the loop.
I suggest the following changes to your code:
$easting_list = array();
$northing_list = array();
$context_list = array();
try {
$sql2 = "SELECT area_easting, area_northing, context_number FROM excavation.contexts";
$sth = $conn->prepare($sql2);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
{
$easting_list[] = $row['area_easting'];
$northing_list[] = $row['area_northing'];
$context_list[] = $row['context_number'];
}
}
catch(PDOException $e )
{
echo "Error: ".$e;
}
echo "context list: ";
echo implode(', ', $context_list);
Now all the values are stored in 3 arrays. explode is used to print a comma-separated list of all values in $context_list array.

Prepare content does not work for Sourcerer and DirectPHP

In my Joomla website, I need to execute some custom SQL queries, that have to select different titles from related categories.
Problem I have it works like option Prepare Content is turned off, so all of my content is outside HTML tags.
Module content looks like this:
{source}
<?php
$var_result = '';
$var_categories = array();
$var_category_list = array();
$db =& JFactory::getDBO();
$query = 'select * from jneg_categories where parent_id = 9';
$db->setQuery($query,0,300);
$res = $db->loadObjectList();
foreach ( $res as $row ) {
$var_categories[($row->id)] = $row->title;
$var_category_list[] = $row->id;
}
$var_category_list = implode($var_category_list, ', ');
$sql = "select * from jneg_content where catid IN (".$var_category_list.") order by `catid`";
$db->setQuery($sql,0,30000);
$res = $db->loadObjectList();
$var_current_cat = 0;
foreach ( $res as $row ) {
if ($current_cat != $row->catid) {
$current_cat = $row->catid;
echo '<h2>'.$categories[($row->catid)] . '</h2>';
echo '<br>';
}
echo $row->title;
echo '<br>';
}
?>
{/source}
Can you help me how to get proper HTML as a result of this code please.
Sourcer or other php rendering plugins don't run in html modules unless you go under the module 'options' and select 'prepare content'...
...or you can use this module and just include your php file directly:
https://github.com/idea34/mod_show
Ok, I did it with Jumi plugin - http://2glux.com/projects/jumi/usage-for-j15
Thank you anyway.

Access Form values in my Symfony executeAction backend

So one of my pages consists of a quiz form that has several questions of type multiple choice, the choices are specified as radio buttons. I have been scanning the Symfony documentation to find out how to access form field values inputted by the user. Thing is, this isn;t a doctrine or propel based form, and neither do I require the values to be stored in the database, hence executing a $form->save() makes little sense to me. But I do require access to specific values of my form in my backend once the user hits submit.
Most of Symfony documentation that i have run into doesn't necessarily explain how this can be done. I would assume it would be something to the effect of :
$request->getParameter( 'radio_choices_id selected value ').
Thanks to all who read this and Cheers to the ones who respond to it :)
Parijat
Hm, it is very simple if I understand your question right)
For widget:
$this->widgetSchema['name'] = new sfWidgetFormChoice(array('choices' => array('ch_1', 'ch_2')));
Ok,in action:
$this->form = new FaqContactForm();
if ($request->isMethod('post')) {
$this->form->bind($request->getParameter($this->form->getName()));
if ($this->form->isValid()) {
$your_val=$this->form->getValue('name');
//or
$your_val=$this->form['name']->getValue());
}
}
In backend in protected function processForm(sfWebRequest $request, sfForm $form)
you have
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';
try {
$product = $form->save();
} catch (Doctrine_Validator_Exception $e) {
$errorStack = $form->getObject()->getErrorStack();
$message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
foreach ($errorStack as $field => $errors) {
$message .= "$field (" . implode(", ", $errors) . "), ";
}
$message = trim($message, ', ');
$this->getUser()->setFlash('error', $message);
return sfView::SUCCESS;
}
Before $product = $form->save(); try
$your_val=$form->getValue('name');
//or
$your_val=$form['name']->getValue());