0

How to insert XML to Mysql with php?

I want to insert data in tag count to xml_id field and data in tag image to image_url field to Mysql. I tried this code with xml file, but didnt' work. What am I doing wrong with code. Please tell me.

Here is XML.

<?xml version="1.0" encoding="utf-8"?>
<Listing>
 <Listing>
 <count>1</count>
 <Ad_Type>Sale</Ad_Type>
 <Unit_Type>Apartment</Unit_Type>
 <Images>
  <image>http://example.com/watermark?c_id=1110&l_id=1908007&aid=1461&image=e296915d71.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1908007&aid=1461&image=acf49f1088.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1908007&aid=1461&image=10a639c856.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1908007&aid=1461&image=9f9db4243e.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1908007&aid=1461&image=v127aca728.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1908007&aid=1461&image=g19bdac010.jpg</image>
 </Images>
 </Listing>

 <Listing>
 <count>2</count>
 <Ad_Type>Sale</Ad_Type>
 <Unit_Type>Apartment</Unit_Type>
 <Images>
  <image>http://example.com/watermark?c_id=1110&l_id=1907998&aid=1461&image=vv96915d71.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1907998&aid=1461&image=g19bdac010.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1907998&aid=1461&image=8127aca728.jpg</image>
  <image>http://example.com/watermark?c_id=1110&l_id=1907998&aid=1461&image=9f9db4243e.jpg</image>
 </Images>
 </Listing>
</Listing>

This is my code.

<?php
include("connection.php");

$xmlUrl = "import_dubai.xml"; // XML ไฟล์   
$xmlStr = file_get_contents($xmlUrl);  
$xml = preg_replace('#&(?=[a-z_0-9]+=)#', '&amp;', $xmlStr);

foreach($xml -> Listing as $Listing1){       // Listing => array

   foreach($Listing1 -> Listing as $Listing){    // Listing => array

    $Listing = $Listing -> Listing;
    $count = $Listing -> count;    

       foreach($Listing -> Images as $Images){   // Images => array

    $image = $Images -> image;
    echo '<br>'.$Listing1 -> Listing.' '.$Listing -> count.' '.$Listing -> Images.' '.$Images -> image. '<br>';
    $result=mysql_query("insert into xml_image ('xml_id','image_url') values ('$count','$image')");
  }
       
   }
}

if (!$result){
 echo 'Mysql Error';
} else{
    echo ' Success'; 
}

?>
Sine
  • 3
  • 2
  • What you announce as XML in your question actually is not valid XML. I assume this broken data causes you such a problem. Fix the data and you should be good to go. – hakre Nov 24 '14 at 13:03
  • Also it is important that you ask as concretely as possible your question. E.g. you've put in the question your whole task, however the error you have is just much more local. To be precise about such more local parts, it's always a good advice to show the error message. See as well: [How to get useful error messages in PHP?](http://stackoverflow.com/q/845021/367456). – hakre Nov 24 '14 at 13:08

2 Answers2

6

I have intoduced a error handler for the provided xml file, so that you can get a more detailed info of what is actually happening or whats wrong with your xml content. Please check this out

<?php
include("connection.php")

$xmlUrl = "import_dubai.xml"; // XML ไฟล์
list ($xml, $error) = parseFile($xmlUrl);
if ($xml === FALSE) {
  throw new Exception("Failed to parse your XML file: $error");
}

foreach($xml -> Listing as $Listing1){       // Listing => array
foreach($Listing1 -> Listing as $Listing){    // Listing => array
   $Listing = $Listing -> Listing;
   $count = $Listing -> count;              
   foreach($Listing -> Images as $Images){   // Images => array
      $image = $Images -> image;
      echo '<br>'.$Listing1 -> Listing.' '.$Listing -> count.' '.$Listing -> Images.' '.$Images -> image. '<br>';
      $result=mysql_query("insert into xml_image ('xml_id','image_url') values ('$count','$image')");
    }

  }
}

if (!$result){
  echo 'Mysql Error';
} else{
  echo ' Success';  
}

 function parseFile($file) {
  $xml = FALSE; // SimpleXMLElement
  $error = FALSE; // string

  if (! file_exists($file)) {
    $error = 'File ' . $file . ' does not exist.';
  } else {
     $oldLibXMLErrors = libxml_use_internal_errors();
     libxml_use_internal_errors(TRUE);

     $xml = simplexml_load_file($file, 'SimpleXMLElement', LIBXML_NOCDATA);
     if ($xml === FALSE) {
       $errors = libxml_get_errors();
       foreach ($errors as $error) {
         if ($error->level != LIBXML_ERR_ERROR && $error->level != LIBXML_ERR_FATAL) {
           continue;
       }

       $parts = array();
       if ($error->file) {
       $parts[] = "File=$error->file";
     }
     $parts[] = "Line=$error->line";
     $parts[] = "Column=$error->column";
     $parts[] = "Code=$error->code";

     $messages[] = implode(" ", $parts) . ": " . trim($error->message);
   }
   $error = implode("\n", $messages);
  }

  libxml_use_internal_errors($oldLibXMLErrors);
  }

  return array($xml, $error);
}
Monish Deb
  • 331
  • 2
  • 5
  • Thank you for your aswer but it have Fatal error: Uncaught exception 'Exception' with message 'Failed to parse your XML file: File=import_dubai.xml Line=42 Column=50 Code=23: EntityRef: expecting ';' File=import_dubai.xml Line=42 Column=62 Code=23: EntityRef:....../opt/lampp/htdocs/uploadxml/import_image_test.php on line 7 how i correct it? – Sine Nov 24 '14 at 09:16
  • (Fatal error is intended by the use of 'throw Exception..' use print_r($error) instead) I see, '&' is the main culprit here thats why you used $xml = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlStr); Instead of that can you use any other special character as a delimiter (in place of & use e.g. '|' or utf-8 character) i.e. acceptable in xml, and later, just before calling the INSERT query replace it with '&' [like $image = str_replace('|', '&', $Images -> image))] – Monish Deb Nov 24 '14 at 10:47
  • I tried $xmlReplace = preg_replace('#&(?=[a-z_0-9]+=)#', '|', $xmlUrl); list ($xml, $error) = parseFile($xmlReplace); and $image = str_replace('|', '&', $Images -> image); before INSERT query but still Fatal earror like before. – Sine Nov 25 '14 at 04:27
  • No what I was saying is that you need to first edit your xml file and change '&' to other special character. And then use$image = str_replace('|', '&', $Images -> image)) (where '|' is the special character) – Monish Deb Nov 25 '14 at 10:36
  • Sorry for my poor English. may i don't understand what you saying. I will try undertand it. whatever thank you for advice and help . I will try to do that. :) – Sine Nov 25 '14 at 11:07
0

This line:

$xml = preg_replace('#&(?=[a-z_0-9]+=)#', '&amp;', $xmlStr);

returns a string, not objects that you can traverse by using

foreach ($xml->Listing as $Listing1) ...

if you want to go with working with XML then you an extra step :

$formatted = preg_replace('#&(?=[a-z_0-9]+=)#', '&amp;', $xmlStr);
$xml = simplexml_load_string($formatted);

That will take you in the right direction.

Konstantin
  • 3,294
  • 21
  • 23
  • i aready try $xml = simplexml_load_string($xmlStr); but have Warning: simplexml_load_string(): Entity: line 42: parser error : EntityRef: expecting ';' in /opt/lampp/htdocs/uploadxml/import_image_test11.php on line 18 Warning: simplexml_load_string(): http://crm.propspace.com/watermark?c_id=1110&l_id=1908007&aid=1461&id=1409335977 in /opt/lampp/htdocs/uploadxml/import_image_test11.php on line 18 I think my image url have & – Sine Nov 24 '14 at 07:57
  • @hakre unlike you i did not read all existing questions and answers on SO and i also did not copy code from duplicate questions. I saw missing code line and informed OP of it. So if you have anything useful to say than say it but don't tell others to 'just do this or that'. – Konstantin Nov 24 '14 at 14:01
  • @Konstantin: I didn't read all and thanks to your comment it turns out I confused the `preg_replace` line in here. So I stand corrected. My applologies I didn't wanted to offense you. It's part of what I commented: Such kind of questions create a lot of fuzz just for the OP having problem to pinpoint the actual issue. Not your fault however. – hakre Nov 24 '14 at 14:16
  • Good morning Konstantin.. I tried $formatted = preg_replace('#&(?=[a-z_0-9]+=)#', '&', $xmlStr); $xml = simplexml_load_string($formatted); but did't work. have many warning. - Warning: simplexml_load_string(): Entity: line 198: -Warning: simplexml_load_string(): -Notice: Trying to get property of non-object in .. -Warning: Invalid argument supplied for foreach() -Notice: Undefined variable: result in /opt/lampp/.../test13.php on line 23 Please advice me for that..sorry for my poor English . – Sine Nov 25 '14 at 04:39
  • Break your problem into little parts. And do one thing at at time. comment out all code below the line that you work on, that way there will not be many error messages First you need to check whether your xml is valid. Try running it through a online validator. Then you can handle converting it to XML object. Once that works you can work on iterating through it. and so on – Konstantin Nov 25 '14 at 06:41
  • Thank you . I will try and back with result. – Sine Nov 25 '14 at 06:50
  • @Konstantin Thank you for help and good advice. I tried corrected and it work. :) thank you so much – Sine Nov 25 '14 at 10:33