首页 > 解决方案 > 使用 PHP 从 XML 中解析产品描述

问题描述

我有一个大问题,我不知道如何获取产品描述。我做了很多不同的事情,但没有任何效果......我是 XML 的新手。

<NewDataSet>
  <Product>
    <Criteria>Description</Criteria>
    <Value>
      <![CDATA[
        Refill PLA Pearl White&nbsp;&nbsp;600g<br /> PLA filaments are extracted from biodegradable materials. In addition to being environmentally friendly, it is also suitable for lower temperature printing methods that greatly reduce the warpage along the edges of the printed good. The translucent texture and finishing will also add a unique feature to your finished work.<br /> Filament refills come in small sizes for space-economy and can be used at any given notice, allowing 3D printer operators and hobbyists to do their part for environmental protection while exercising their creative powers.
      ]]>
    </Value>
  </Product>
  <Product>
    <Criteria>Vendor Homepage</Criteria>
    <Value>eu.xyzprinting.com/eu_en/Product/PLA</Value>
  </Product>
</NewDataSet>

我的PHP代码:

foreach($xml23 as $data3){
    $desc = "Description";
    echo $data3 -> Criteria -> $desc -> Value;
}

标签: phpxml

解决方案


您可以使用xpath()来获取<Value>标签的值,它匹配<Criteria>Description</Criteria>

$xml23->xpath('//Product/Criteria[.="Description"]/../Value');

例子:

$xml = '<NewDataSet>
<Product>
    <Criteria>Description</Criteria>
    <Value>
    <![CDATA[
    Refill PLA Pearl White&nbsp;&nbsp;600g<br /> PLA filaments are extracted from biodegradable materials. In addition to being environmentally friendly, it is also suitable for lower temperature printing methods that greatly reduce the warpage along the edges of the printed good. The translucent texture and finishing will also add a unique feature to your finished work.<br /> Filament refills come in small sizes for space-economy and can be used at any given notice, allowing 3D printer operators and hobbyists to do their part for environmental protection while exercising their creative powers.
    ]]>
    </Value>
</Product>
<Product>
    <Criteria>Vendor Homepage</Criteria>
    <Value>eu.xyzprinting.com/eu_en/Product/PLA</Value>
</Product>
</NewDataSet>';

$xml23 = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$elm = $xml23->xpath('//Product/Criteria[.="Description"]/../Value');
echo (string)$elm[0];

输出:

补充装 PLA 珍珠白 600g<br />- PLA 细丝提取...


推荐阅读