【发布时间】:2017-03-01 14:02:24
【问题描述】:
假设我有一个如下所示的 xml 文件:
<objectlist>
<objectcode>OP#0003</objectcode>
<objectid>0001</objectid>
<objecttype>Test object</objecttype>
<object>
<info>
<id>001</id>
<name>Some name</name>
<value>5</value>
</info>
<properties>
<shopdetails>
<desciption>
<header>Test</header>
<text>This is some text about the object</text>
</desciption>
<price>4</price>
<currency>Dollar</currency>
<weight>500</weight>
<gramSymbol>mg</gramSymbol>
</shopdetails>
</properties>
</object>
</objectlist>
如何使用curl_setopt() 从这个 XML 文件中获取所有信息?我用foreach循环尝试过,但失败了。它仅从以下位置获取信息:objectcode、object id 和 objecttype。
我的脚本只能从根的子节点获取信息,但不能从子节点的子节点获取信息。我在我的项目中使用了这个脚本:
<?php
Class xmlObject{
public function xml_From_URL() {
require_once 'dbconnect.php';
$config[CURLOPT_URL] = "http://localhost/example.xml";
$config[CURLOPT_VERBOSE] = 0;
$config[CURLOPT_SSLVERSION] = 3;
$config[CURLOPT_SSL_VERIFYPEER] = FALSE;
$config[CURLOPT_SSL_VERIFYHOST] = 2;
$config[CURLOPT_FOLLOWLOCATION] = 0;
$config[CURLOPT_HEADER] = 0;
$config[CURLOPT_RETURNTRANSFER] = 1;
//-- config section --//
$tuCurl = curl_init();
curl_setopt_array($tuCurl, $config);
$data = curl_exec($tuCurl);
$xml = simplexml_load_string($data);
//-- Loops --//
//-- 1 --//
foreach($xml -> object as $row){
$id = $row -> id;
$name = $row -> name;
$value = $row -> value;
echo("<b>Objects</b></br>");
echo($id."<br>");
echo($name."<br>");
echo($value."<br>");
}
//-- 2 --//
foreach ($xml -> description as $row) {
$header = $row -> header;
$text = $row -> text;
echo("<b>description</b><br>");
echo($header);
echo($text);
}
//-- 3 --//
foreach ($xml -> shopdetails as $row) {
$header = $row -> price;
$text = $row -> currency;
$weight = $row -> weight;
$gramsymbol = $row -> gramsymbol;
echo("<b>description</b><br>");
echo($header);
echo($text);
}
curl_close($tuCurl);
}
}
?>
【问题讨论】: