drxkx6149 2015-12-03 16:31
浏览 149

php和xml不能正常工作simplexml_load_string

Hello I have been trying a lot of loading xml via php but from my vps error log I always got error.

PHP Warning: Invalid argument supplied for foreach() Trying to get property of non-object

So far this what I have created

xml.php
<?php

$url = "test.xml";
$ch = curl_init();
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);

$data = curl_exec ($ch);
curl_close($ch);

$xml = simplexml_load_string($data);

$con = mysql_connect("localhost","root","mypassw0rd");
mysql_select_db("test_xml",$con) or die(mysql_error());

foreach($xml -> item as $row){
    $title = $row -> title;
    $destination = $row -> destination;
    $price = $row -> price;


mysql_query("INSERT INTO `tblxml` VALUES('NULL','$title','$destination','$price')") or die(mysql_error());

}

?>

test.xml

<item>
    <title>
    title 1
    </title>

    <destination>
    destination 1
    </destination>

    <price>
    price 1
    </price>
</item>

table structure

CREATE TABLE IF NOT EXISTS `tblxml` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` text NOT NULL,     
  `destination` text NOT NULL,
  `price` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;

xml and php both on the same folder.

Any help would appreciate.

  • 写回答

1条回答 默认 最新

  • dongzhiyan5693 2015-12-03 16:45
    关注

    Having read your question again, there are really a couple of serious flaws with it.

    1. Please read a good tutorial on XML/SimpleXML/DomDocument
    2. As mentionned, use the newer mysqli_ functions, PDO and binding
    3. What's the purpose of fetchting an XML file locally with curl ?
    4. Your query won't work, you did not specify the fields and you do not need to insert NULL values (though it will work). This is the skeleton for an INSERT query in MySQL:
    INSERT INTO `table` (`field1`, ..., `fieldx`) VALUES('$value1', ... '$valuex');
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大