SimpleXML inserting new line - php

Have this sample.xml:
<FacturacionAR>
<Factura xsi:type="FacturaAR">
<TipoNota>Boleta de Ventas y Servicios</TipoNota>
<Agencia>LUIL</Agencia>
<NroFactura>5040</NroFactura>
<Cliente>JOHAO SMITH CART</Cliente>
<Ciudad>NUNORK</Ciudad>
<Direccion>CALLE VITAL DE MELLO</Direccion>
<Barrio>JAJJKIU</Barrio>
<Estado>Cancelada</Estado>
</Factura>
</FacturacionAR>
I want to add "Telefono" every time this node is missing, just after "Barrio", so I tried to do in php:
$filename = "sample.xml";
$FacturacionAR = simplexml_load_file($filename,null,true);
function simplexml_insert_after(SimpleXMLElement $sxe, SimpleXMLElement $insert, SimpleXMLElement $target)
{
$target_dom = dom_import_simplexml($target);
$target_dom->formatOutput = true;
$target_dom->preserveWhiteSpace = false;
$insert_dom = $target_dom->ownerDocument->importNode(dom_import_simplexml($insert), true);
if ($target_dom->nextSibling) {
$result = $target_dom->parentNode->insertBefore($insert_dom, $target_dom->nextSibling);
$target_dom->parentNode->insertBefore($target_dom->ownerDocument->createTextNode("\n"), $result);
return $result;
} else {
return $target_dom->parentNode->appendChild($insert_dom);
}
}
foreach ($FacturacionAR->Factura as $Factura) {
if (!isset($Factura->Telefono)) {
$meta2 = new SimpleXMLElement("<Telefono/>");
$target = current($FacturacionAR->xpath('//Barrio[last()]'));
simplexml_insert_after($FacturacionLocalizaAR, $meta2, $target);
}
}
The expected result is:
<Barrio>JAJJKIU</Barrio>
<Telefono></Telefono>
But when I run the php script, this error appears:
PHP Catchable fatal error: Argument 3 passed to simplexml_insert_after() must be an instance of SimpleXMLElement, boolean given
Any ideas?

OK. Upgrading to PHP 5.5.3 solved my problem.

Related

Importer issue Invalid argument supplied for foreach()

I've a CSV files importer so the user can update the categories of the articles for the store they work for.
While the file is being processed, Laravel throws me this error:
Invalid argument supplied for foreach()
This is my Controller code:
public function procesar(ImportarCategoriasArticulos $importador){
list( $ruta,$nombre_excel ) = explode('/', $importador->excel_ruta);
ini_set('memory_limit', -1);
ini_set('max_execution_time', -1);
//dd($importador);
try{
CategoriaArticulos::query()->truncate();
Excel::import(new CategoriasArticulosImportador, public_path().'/storage/uploads/'.$nombre_excel);
$articulos_no_encontrados = CategoriaArticulos::select(['codigo_interno'])->distinct()->whereNull('articulo_id')->get();
if( $articulos_no_encontrados->count() > 0 ){
$importador->articulos_no_encontrados = $articulos_no_encontrados->toJson();
$importador->estatus = 'procesado con error';
$importador->save();
\Alert::error(trans('ERROR: Existen articulos no encontrados.'))->flash();
return redirect('admin/configuracion/importar_categoria_articulos/'.$importador->id);
} else {
Articulo::all()->map( function( $articulo ){
$nuevos_datos = CategoriaArticulos::where('articulo_id', $articulo->id)->first();
$articulo->categoria = $nuevos_datos->categoria;
$articulo->subcategoria = $nuevos_datos->subcategoria;
$articulo->subsubcategoria = $nuevos_datos->subsubcategoria;
$articulo->save();
});
\Artisan::command('key-a:sm:generar-categorias');
$importador->estatus = 'procesado con exito';
$importador->save();
\Alert::success(trans('EXITO: se modificaron las categorias.'))->flash();
return redirect('admin/configuracion/importar_categoria_articulos/');
}
} catch (\Exception $e){
\Alert::error(trans($e->getMessage()))->flash();
return redirect('admin/configuracion/importar_categoria_articulos/');
}
}
Could you please help me find what is wrong? I've done importers before but this time seems impossible to me.
Thanks in advance.

Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, null given,

I am unable to export my mysql table to XML format using PHP, I receive the following error when I run the below script. I have removed the connection bit, I have gone through already errors but was not able resolve this issue.
Catchable fatal error: Argument 1 passed to DOMNode::appendChild() must be an instance of DOMNode, null given,
Script:
<?php
$query = "SELECT id, name, plate, datetime , time , image_name FROM EarlsdonMSIN_anpr_vega";
$camArray = array();
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
array_push($camArray, $row);
}
if(count($camArray)){
createXMLfile($camArray);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
function createXMLfile($camArray){
$filePath = '/cam.xml';
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('cam');
for($i=0; $i<count($camArray); $i++){
$camId = $camArray[$i]['id'];
$camName = $camArray[$i]['name'];
$camplate = $camArray[$i]['plate'];
$camdatetime = $camArray[$i]['datetime'];
$camtime = $camArray[$i]['time'];
$camimagename = $camArray[$i]['image_name'];
$cam = $dom->createElement('cam');
$cam->setAttribute('id', $camId);
$name = $dom->createElement('name', camName);
$cam->appendChild($name);
$plate = $dom->createElement('plate', $camplate);
$cam->appendChild($plate);
$datetime = $dom->createElement('datetime', $camdatetime);
$cam->appendChild($datetime);
$time = $dom->createElement('time', $camtime);
$cam->appendChild($time);
$imagename = $dom->createElement('image_name', $camimagename); $cam->appendChild($image_name);
$root->appendChild($cam);
}
$dom->appendChild($root);
$dom->save($filePath);
}

Fatal error: Call to a member function find() on a non-object in /home/path/index.php on line 170

I get this error and the line 170 has this code
$tonton = count($veriler) - 1;
as more :
$ek = $_POST['kk']."?page=".$_POST['sayfa'];
$al = get_data("http://www.example.com/".$ek);
$dom = str_get_html($al);
$veriler = $dom->find('.videoBox');
$tonton = count($veriler) - 1;
$sondo = $_POST['adet'] + 5;
if($sondo <= count($veriler)-1)
{
$sondon = $sondo;
}
else
{
$sondon = count($veriler) - 1;
}
do you have any idea where can be the problem because this script works on all my sites but only in one server I get this arror and I'm using simple_html_dom.php
with php version 5.4.34
thankyou
Try this
$ek = "http://www.xxxxxxxxxx.com/".$_POST['kk']."?page=".$_POST['sayfa'];
$dom = file_get_html($ek);
The variable $dom is not set (null). You should investigate yourself why this is the case

CodeIgniter Sqlite not working

Whenever I query my database (sqlite) like this in my model (im using codeigniter, full code below):
$this->db->select('post');
$query = $this->db->get('posts');
return $query->result_array();
I get the following error:
Fatal error: Call to a member function rowCount() on a non-object in /codeigniter/system/database/drivers/pdo/pdo_result.php on line 42
When changing the query to something nonexistent I get a "proper" error, something like:
A Database Error Occurred
Error Number: HY000
no such column: posst
SELECT posst FROM posts
Filename: /codeigniter/models/post.php
Line Number: 8
Which leads me to believe the database is actually working, but there is something I am missing.
I have tried recreating the database. It literally has 1 table with 1 column, but I just cannot get any data out. I also tried creating it with different "admin" programs but to no avail. I made sure it is an Sqlite 3 db, which is supported by the webserver according to phpinfo.
Does anybody have a clue where I am making a mistake?
-------- full code:
my post model in models/post.php
<?php
class Post extends CI_Model{
function get_posts(){
$this->db->select('posst');
$query = $this->db->get('posts');
return $query->result_array();
}
}
My controller in controller/posts.php :
<?php
class Posts extends CI_Controller{
function index(){
$this->load->model('post');
$data['posts']=$this->post->get_posts();
echo"<pre>";
print_r($data['posts']);
echo"</pre>";
}
}
My database config in database.php :
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'sqlite:/home/******/******/www/wtp3/codeigniter/db/wtp35.sqlite';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'pdo';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
Credits for this fix are with S. Stüvel, J. Bransen and S. Timmer. This is a fix for a specific server, so YMMV. It did the trick for me though.
In pdo_driver.php, starting line 81 change:
empty($this->database) OR $this->hostname .= ';dbname='.$this->database;
$this->trans_enabled = FALSE;
$this->_random_keyword = ' RND('.time().')'; // database specific random keyword
}
to
if(strpos($this->database, 'sqlite') !== FALSE) {
$this->hostname = $this->database;
$this->_random_keyword = ' RANDOM()';
}
else {
$this->hostname .= ";dbname=".$this->database;
$this->_random_keyword = ' RND('.time().')'; // database specific random keyword
}
$this->trans_enabled = FALSE;
}
On line 189 change the entire function _execute($sql) to
function _execute($sql)
{
$sql = $this->_prep_query($sql);
$result_id = $this->conn_id->query($sql);
if (is_object($result_id))
{
$this->affect_rows = $result_id->rowCount();
}
else
{
$this->affect_rows = 0;
}
return $result_id;
}
Then in pdo_result.php change":
On line 29 change
public $num_rows;
to
var $pdo_results = '';
var $pdo_index = 0;
on line 36 replace entire function
public function num_rows()
{
if (is_int($this->num_rows))
{
return $this->num_rows;
}
elseif (($this->num_rows = $this->result_id->rowCount()) > 0)
{
return $this->num_rows;
}
$this->num_rows = count($this->result_id->fetchAll());
$this->result_id->execute();
return $this->num_rows;
}
with:
function num_rows()
{
if ( ! $this->pdo_results ) {
$this->pdo_results = $this->result_id->fetchAll(PDO::FETCH_ASSOC);
}
return sizeof($this->pdo_results);
Then on line 60 change
function num_fields()
{
return $this->result_id->columnCount();
}
to:
function num_fields()
{
if ( is_array($this->pdo_results) ) {
return sizeof($this->pdo_results[$this->pdo_index]);
} else {
return $this->result_id->columnCount();
}
}
Then on line 94 change:
function field_data()
{
$data = array();
try
{
for($i = 0; $i < $this->num_fields(); $i++)
{
$data[] = $this->result_id->getColumnMeta($i);
}
return $data;
}
catch (Exception $e)
{
if ($this->db->db_debug)
{
return $this->db->display_error('db_unsuported_feature');
}
return FALSE;
}
}
to:
function field_data()
{
if ($this->db->db_debug)
{
return $this->db->display_error('db_unsuported_feature');
}
return FALSE;
}
then line 146 change:
return FALSE;
to
$this->pdo_index = $n;
then on line 159 change
function _fetch_assoc()
{
return $this->result_id->fetch(PDO::FETCH_ASSOC);
}
to
function _fetch_assoc()
{
if ( is_array($this->pdo_results) ) {
$i = $this->pdo_index;
$this->pdo_index++;
if ( isset($this->pdo_results[$i]))
return $this->pdo_results[$i];
return null;
}
return $this->result_id->fetch(PDO::FETCH_ASSOC);
}
And finally on line 174 change:
function _fetch_object()
{
return $this->result_id->fetchObject();
to
function _fetch_object()
{
if ( is_array($this->pdo_results) ) {
$i = $this->pdo_index;
$this->pdo_index++;
if ( isset($this->pdo_results[$i])) {
$back = new stdClass();
foreach ( $this->pdo_results[$i] as $key => $val ) {
$back->$key = $val;
}
return $back;
}
return null;
}
return $this->result_id->fetch(PDO::FETCH_OBJ);
}
This worked for me. Again, not my work, credit goes out to S. Stüvel, J. Bransen and S. Timmer.
Rather long answer, but i hope this helps.
There is a bug in CodeIgniter version 2.1.0 for PDO drivers (They had just added PDO driver in version 2.1.0)
You can see change log for version 2.1.1
Please try upgrading your CodeIgniter.
I have Codeigniter 2.2.1 and when I set application/config/database.php the same as OP I can use sqlite database, sort of. I can create new database/file, create new tables and insert data. The problem is that I can't read any.
$query = $this->db->get('table_name');
return $query->result_array();
Returns empty array. The same happens when I do.
$query = $this->db->query("SELECT...");
Apparently there are still some bugs. I'm just starting to explore Codeigniter, but when I switch to mysql the same exact Model works as it should.
For the record, everything on my server is set up OK. I can use my sqlite databases just fine, it is just Codeigniter that has problems.
I applied g_m solution after updating from 2.1.3 to 2.2.6, and as jimmy, I had to remove the first change in pdo_driver.php to make it work.

I cannot call asp.net web service in php

I created web service using asp.net framework 4 :
[WebMethod]
public DataSet GetMembers(string memberId, string thirdName)
{
string connStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
SqlConnection cn = new SqlConnection(connStr);
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand(#"SELECT MemberMaster.MemberId,MemberMaster.FirstName,MemberMaster.SecondName,MemberMaster.ThirdName,MemberMaster.CivilNo,MemberMaster.DateOfBirth,MemberSubcription.MemberId
FROM MemberMaster inner join MemberSubcription on MemberMaster.MemberId=MemberSubcription.MemberId
WHERE MemberMaster.MemberId=#MemberId and MemberMaster.ThirdName=#ThirdName", cn);
da.SelectCommand.Parameters.Add("#MemberId", SqlDbType.NVarChar).Value = memberId;
da.SelectCommand.Parameters.Add("#ThirdName", SqlDbType.NVarChar).Value = thirdName;
ds.Clear();
da.Fill(ds);
return ds;
}
it work good in localhost but when i call it in the php :
<?php
$wsdlUrl = "http://xxxx/WS/WebService.asmx?WSDL";
$client = new soapclient($wsdlUrl);
$params = array('memberId' => 'W1100045','thirdName' => 'Ali');
$result = $client->GetMembers($params);
$echoText = '';
if (is_null($result->GetMembersResult))
{
echo "no result";
}
else
{
echo $result->GetMembersResult;
}
?>
this error appear :
Catchable fatal error: Object of class stdClass could not be converted to string on line 23
what is the problem and how can i solve this problem ?

Categories