我有大约60000个xml文件,我必须插入到MySQL数据库。因此,我考虑制作一个简单的PHP脚本,该脚本将被执行一次,从这个XML文件加载数据并将其插入到本地主机上的数据库中。
在插入它到我的DB之前,我试图在页面上的数据上显示它们,但它没有显示任何内容,其类型为NULL。
下面是代码:<?php
$dir = new DirectoryIterator('organismes');
foreach ($dir as $fileinfo) {
if (!$fileinfo -> isDot()) {
$XMLFILE = $fileinfo -> getFilename();
echo $XMLFILE . "<br>'n"; /*the filename shows correctly, so the DirectoryIterator is working*/
$pathtofile = "http://localhost/www/organismes/$XMLFILE"; /*the link to the xml file made with a variable*/
echo $pathtofile . "<br>'n"; /* the link shown is correct */
$xml = simplexml_load_file($pathtofile);
echo gettype($xml) . "<br>'n";
if ($xml == FALSE) {
echo "failed to load xml"; /* this message never shows so the xml file loads correctly */
} else {
$Org = $xml->Organisme->Nom; //this variable $Org gets a NULL Value
echo $Org . "<br>" ;
echo gettype($Org);
}
}
}
?>
当我使用print_r($xml)时,它会显示一些数据,因此文件可以正确加载。这里有一个XML文件的例子:
<Organisme id="adil-01053-01" codeInsee="01053" dateMiseAJour="2013-02-27" pivotLocal="adil">
<Nom>Agence</Nom>
<EditeurSource>A2 A3</EditeurSource>
<Adresse type="géopostale">
<Ligne>34, rue du Général-Delestraint</Ligne>
<CodePostal>01000</CodePostal>
<NomCommune>Bourg-en-Bresse</NomCommune>
<Localisation>
<Latitude>46.196535</Latitude>
<Longitude>5.2191997</Longitude>
<Précision>6</Précision>
</Localisation>
<Accessibilité type="ACC"/></Adresse>
<CoordonnéesNum>
<Téléphone>00000000000</Téléphone>
<Télécopie>00000000000</Télécopie>
<Email>adil.01@wanadoo.fr</Email>
<Url>http://www.adil01.org</Url>
</CoordonnéesNum>
<Ouverture><PlageJ début="vendredi" fin="vendredi"><PlageH début="09:00:00" fin="17:00:00"/></PlageJ><PlageJ début="lundi" fin="jeudi"><PlageH début="09:00:00" fin="18:00:00"/></PlageJ>
</Ouverture>
</Organisme>
所以我想弄清楚为什么它不能正确显示,为什么它得到一个NULL值所以兄弟们,如果你能帮忙的话,那就太好了:)
$pathtofile = "http://www.w3schools.com/xml/note.xml";
$xml = simplexml_load_file($pathtofile);
if ($xml == FALSE) {
echo "failed to load xml";
}
else
{
$A = $xml->to;
echo "$A <br />";
}
只关注这部分代码,它似乎工作正确。有两种情况发生。"$xml->Organisme->Nom;"有拼写错误和/或被提取的xml文件不包括这些字段名。
对于测试,请执行
print_r($xml);
之后echo "$A <br />";
以获得被提取的XML文件的准确表示。
我不确定您想要什么,但我假设您想要将XML数据插入到数据库中。如果是这种情况,试试这个:
function create_xml()
{
$xml = simplexml_load_file("file.xml");
$nodes = new SimpleXMLElement('file.xml', null, true)
or die("cannot create");
$i = 0;
foreach ($nodes->children() as $child)
{
$var= $child->xml_child;
$sql = "INSERT INTO ...)";
mysqli_query($connect, $sql);
$i++;
echo "xml set";
}
}