我在访问 XML 中的属性时遇到了一些问题。我的代码如下。最初我有两个循环,这没有问题。
我将首先获取图像名称,然后使用第二个循环来获取故事标题和故事细节。然后将所有内容插入数据库。我想整理代码并只使用一个循环。我的图像名称存储在 Href 属性中。()
示例 XML 布局 (http://pastie.org/1850682)。XML 布局有点混乱,所以这就是使用两个循环的原因。
$xml = new SimpleXMLElement('entertainment/Showbiz.xml', null, true);
// Get story images
//$i=0;
//$image = $xml->xpath('NewsItem/NewsComponent/NewsComponent/NewsComponent/NewsComponent/NewsComponent/ContentItem');
// foreach($image as $imageNode){
// $attributeArray = $imageNode->attributes();
// if ($attributeArray != ""){
// $imageArray[$i] = $attributeArray;
// $i++;
// }
//}
// Get story header & detail
$i=0;
$story = $xml->xpath('NewsItem/NewsComponent/NewsComponent/NewsComponent');
foreach($story as $contentItem){
//$dbImage = $imageArray[$i]['Href'];
foreach($contentItem->xpath('ContentItem/DataContent/nitf/body/body.head/hedline/hl1') as $headline){
$strDetail = "";
foreach($contentItem->xpath('ContentItem/DataContent/nitf/body/body.content/p') as $detail){
$strDetail .= '<p>'.$detail.'</p>';
foreach($contentItem->xpath('NewsComponent/NewsComponent/ContentItem') as $imageNode){
$dbImage = $imageNode->attributes();
}
}
$link = getUnique($headline);
$sql = "INSERT INTO tablename (headline, detail, image, link) VALUES ('".mysql_real_escape_string($headline)."', '".mysql_real_escape_string($strDetail)."', '".mysql_real_escape_string($dbImage)."', '".$link."')";
if (mysql_query($sql, $db) or die(mysql_error())){
echo "Loaded ";
}else{
echo "Not Loaded ";
}
}
$i++;
}
我想我快要得到它了。我尝试在第四个嵌套的 foreach 循环中放置一些 echo 语句,但没有任何结果。所以它没有执行那个循环。我已经在这工作了几个小时,也用谷歌搜索,只是无法得到它。
如果一切都失败了,我将回到使用两个循环。
问候,斯蒂芬