如何从XML循环中获取数组数据

时间:2017-06-07 03:56:56

标签: php arrays xml loops foreach

我有XML格式的sparql输出:`

<sparql xmlns="http://www.w3.org/2005/sparql-results#">
<head>
    <variable name="Keyword2"/>
</head>
<results ordered="false" distinct="false">
    <result>
        <binding name="Keyword2">
            <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Soga_Jawa</uri>
        </binding>
    </result>
    <result>
        <binding name="Keyword2">
            <uri>http://www.semanticweb.org/g/ontologies/2010/0/OntologiBatikTanty#Warna_Alami</uri>
        </binding>
    </result>
</results>
</sparql>

`

我在php中使用这样的循环:`

$xml = simplexml_load_string($hasil) or die ("error cannot create object");
$results = $xml->results->result;
$jumlah=count($results);
echo "Total hasil pencarian : $jumlah <br><br>";
//$keyword2=array();
$output=array();
foreach($xml->results->result as $nodes){
$jumlah=count($nodes);
    foreach ($nodes->binding as $key =>$node) {
      $output=$node->uri;
      echo $output;
      echo "<br><br>";
      echo $keyword=substr($output,66);
      echo "<br><br>";  
    }
    }
    echo"<hr>";
    echo $keyword[0];

`

我的问题是如何从外部循环访问数据数组。例如,我想访问索引[0]。但输出只有“W”它应该是“Soga_Jawa”

1 个答案:

答案 0 :(得分:0)

解决了您的问题,请查看此代码

$xml = simplexml_load_string($hasil) or die ("error cannot create object");
$results = $xml->results->result;
$jumlah=count($results);
echo "Total hasil pencarian : $jumlah <br><br>";
//$keyword2=array();
$output=array();
$keyword = array();
foreach($xml->results->result as $nodes){
$jumlah=count($nodes);
    foreach ($nodes->binding as $key =>$node) {
      $output=$node->uri;
      echo $output;
      echo "<br><br>";
      echo $keyword[]=substr($output,66);
      echo "<br><br>";  
    }
    }
    echo"<hr>";
    echo $keyword[0];

使用关键字作为数组类型并将其置于循环之外