Я пытаюсь получить XML-информацию из URL-адреса для импорта в mysql через php-скрипт, но у меня возникают некоторые проблемы, и мой опыт не покрывает эту область. В качестве примера используется 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 и т.д. Dosen't echo любые значения.
Edit2: нужно было проверить высокий массив, это работает.
Он имеет отношение к префиксу пространства имен, который вы хотите. Вы можете получить доступ к таким элементам g:
<?php
$str_xml = file_get_contents('test.xml');
$library = new SimpleXMLElement($str_xml);
$count = 0;
foreach ($library->channel->item as $shelf)
{
$gId = (string) $shelf->title;
$Title = (string) $shelf->children('g', TRUE)->id;
$gProductType = (string) $shelf->children('g', TRUE)->product;
echo $gId."<br />";
echo $Title."<br />";
echo $gProductType."<br />";
$count ++;
}
echo " Counted: " . $count . " inserts";
?>
См. Https://www.sitepoint.com/simplexml-and-namespaces/ для дальнейшей справки.
xml.test
<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:g="http://base.google.se/ns/1.0">
<channel>
<title>product</title>
<description>lots of products</description>
<link>www.example.com</link>
<item>
<g:id>ID 1</g:id>
<title>Title 1</title>
<g:product>Product 1</g:product>
</item>
<item>
<g:id>ID 2</g:id>
<title>Title 2</title>
<g:product>Product 2</g:product>
</item>
</channel>
</rss>
Выход:
Название 1
ID 1
Продукт 1
Название 2
ID 2
Продукт 2
Подсчитано: 2 вставки