如何从xml提取值到php

时间:2018-09-20 07:31:11

标签: php xml

<?xml version="1.0"?>
<ABCD xmlns="http://abcd.com">
<PRODUCT xmlns="">
 <CNHEADER>
  <CNTRACK>true</CNTRACK>
  <FIELD name="PRODUCTNO" value="BK201122"/>
  <FIELD name="ProductType" value="DP"/>
  <FIELD name="strProdCode" value="NL1754"/>

在这里,我想要PRODUCTNO等的值。

我尝试了这个,但是仍然没有任何输出

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_URL, $url); // get the url contents 

$data = curl_exec($ch); // execute curl request 

curl_close($ch); 

$xml = simplexml_load_string($data); 

echo $value = (string) $xml->FIELD[0]->attributes()->name; 

1 个答案:

答案 0 :(得分:1)

使用SimpleXMLElement()可以从xml字符串获取产品数据; ref

// Your xml string
$xmlString = '<?xml version="1.0"?>
<ABCD xmlns="http://abcd.com">
<PRODUCT xmlns="">
 <CNHEADER>
  <CNTRACK>true</CNTRACK>
  <FIELD name="PRODUCTNO" value="Z41346020"/>
  <FIELD name="ProductType" value="DP"/>
  <FIELD name="strProdCode" value="NL1754"/>
 </CNHEADER>
</PRODUCT>
</ABCD>';

$xmlData = new SimpleXMLElement($xmlString);

$productData = [];
foreach ($xmlData->PRODUCT->CNHEADER->FIELD as $productField) {
    $productData[(string)$productField{'name'}] = (string)$productField{'value'};
}

echo "<pre>";
print_r($productData);
exit;

您将获得以下输出

// Output
Array
(
    [PRODUCTNO] => Z41346020
    [ProductType] => DP
    [strProdCode] => NL1754
)