为了账号安全,请及时绑定邮箱和手机立即绑定

用PHP读取XML文件,XML文件没有组织

用PHP读取XML文件,XML文件没有组织

PHP
婷婷同学_ 2021-06-29 22:47:36
大家好,我有一个这样的 XML 文件:<?xml version="1.0"?><catalog>   <car>      <title>This is car</title>      <price>44.95</price>      <model>2018</model>      <description>An in-depth look at creating applications with XML.</description>   </car>   <bike>      <title>this is bike</title>      <price>33.58</price>      <description>Just the dummy description</description>   </bike>   <wheels>      <title>this is wheel</title>      <price>33.58</price>      <description>Just the dummy description</description>   </wheels>   <bike>      <title>this is bike</title>      <price>33.58</price>      <description>Just the dummy description</description>   </bike></catalog>我想遍历节点并相应地处理节点。如果是汽车,我需要将汽车详细信息传递给某个函数,如果是自行车,则需要将自行车详细信息传递给另一个函数。关键是根据节点类型(汽车或自行车或其他)处理节点。PHP$z = new XMLReader;$z->open('data.xml');$doc = new DOMDocument;// move to the first <product /> nodewhile ($z->read() && $z->name !== 'product');// now that we're at the right depth, hop to the next <product/> until the end of the treewhile ($z->name === 'product'){    // either one should work    //$node = new SimpleXMLElement($z->readOuterXML());    $node = simplexml_import_dom($doc->importNode($z->expand(), true));    // now you can use $node without going insane about parsing    var_dump($node->element_1);    // go to next <product />    $z->next('product');}如果节点是产品,上面的 PHP 代码工作正常。我需要使用不同的节点。
查看完整描述

1 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

你可以只使用 SimpleXML 来做到这一点:


$xml = simplexml_load_file('data.xml');

foreach ($xml->children() as $product) {

    if ($product->getName() == 'car') {

        carFunc($product->title, $product->price, $product->model, $product->description);

    }

    if ($product->getName() == 'bike') {

        bikeFunc($product->title, $product->price, $product->description);

    }

    if ($product->getName() == 'wheels') {

        wheelFunc($product->title, $product->price, $product->description);

    }

}


function carFunc($title, $price, $model, $description) {

    echo "Car: $title: It's a $model selling for $price. In detail: $description\n";

}


function bikeFunc($title, $price, $description) {

    echo "Bike: $title: It sells for $price. In detail: $description\n";

}


function wheelFunc($title, $price, $description) {

    echo "Wheel: $title: It sells for $price. In detail: $description\n";

}

输出(对于您的示例 XML)


Car: This is car: It's a 2018 selling for 44.95. In detail: An in-depth look at creating applications with XML. 

Bike: this is bike: It sells for 33.58. In detail: Just the dummy description 

Wheel: this is wheel: It sells for 33.58. In detail: Just the dummy description 

Bike: this is bike: It sells for 33.58. In detail: Just the dummy description


查看完整回答
反对 回复 2021-07-02
  • 1 回答
  • 0 关注
  • 130 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信