【发布时间】:2017-12-18 15:29:22
【问题描述】:
我正在尝试从要通过 php 脚本导入 mysql 的 url 获取 xml 信息,但我遇到了一些麻烦,而且我的经验并未涵盖该领域。 XML 形成如下示例:
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:g="http://base.google.se/ns/1.0">
<channel>
<title></title>
<description></description>
<link></link>
<item>
<g:id></g:id>
<title></title>
<g:product></g:product>
</item>
<item>
<g:id></g:id>
<title></title>
<g:product></g:product>
</item>
and so on...
使用 php 脚本:
<?php
include '../connection-to-db.php';
$str_xml = file_get_contents('http://www.example.com/xmls/xmlfile.xml');
$library = new SimpleXMLElement($str_xml);
$arr = json_decode( json_encode($library) , true);
var_dump ($arr);
echo "Array got " .sizeof($arr['item']) . " items.<br> <br>";
if (sizeof($arr['item']) > 155555500) {
mysql_query("TRUNCATE TABLE google_stat");
$count = 0;
foreach ($arr['item'] as $shelf)
{
$gId = mysql_real_escape_string($shelf['g:id']);
$Title = mysql_real_escape_string($shelf['title']);
$gProductType = mysql_real_escape_string($shelf['g:product']);
mysql_query("INSERT INTO google_stat (gid, title, gcategory)
VALUES ('$gID', '$Title', '$gCategory')")
or die(mysql_error());
$count ++;
}
echo " Counted: " . $count . "inserts";
} else {
echo "Non counted, no insert done";
}
?>
问题是当 SimpleXMLElement 似乎所有带有 g: 的项目时,当我查看输出时,名称都消失了,它甚至没有找到任何项目。 我什至尝试过使用具有相同 XML 树的本地文件,但什至无法使其工作。 感谢您提供的任何帮助,因为我越来越意识到自己在这方面陷入了困境。
更新:
<?php
include '../connection-to-db.php';
$str_xml = file_get_contents('http://www.example.com/xmls/xmlfile.xml');
$library = new SimpleXMLElement($str_xml);
$arr = json_decode( json_encode($library) , true);
echo "Array got " .sizeof($library->channel->item) . " items.<br> <br>";
if (sizeof($library->channel->item) > 100) {
mysql_query("TRUNCATE TABLE google_stat");
$count = 0;
foreach ($library->channel->item as $shelf)
{
$gId = (string) $shelf->children('g', TRUE)->id;
$Title = (string) $shelf->title;
$gProductType = $shelf->children('g', TRUE)->product;
echo $gId."<br />";
echo $Title."<br />";
echo $gProductType."<br />";
$count ++;
}
echo " Counted: " . $count . "inserts";
} else {
echo "Non counted, no insert done";
}
?>
现在我得到了数组中的项目数,但是 $gId、$Title 等没有回显任何值。
Edit2:必须进行高位数组检查,才有效。
【问题讨论】:
-
每次在新代码中使用the
mysql_数据库扩展this happens 时,它都已被弃用,并且已经存在多年,并且在 PHP7 中永远消失了。如果您只是学习 PHP,请花精力学习PDO或mysqli数据库扩展和预处理语句。 Start here -
一些合理的代码缩进是个好主意。它可以帮助我们阅读代码,更重要的是,它将帮助 您调试代码 Take a quick look at a coding standard 为您自己谋福利。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
-
插入语句中的
$gCategory来自哪里?