如何使用php搜索XML文件?

时间:2014-10-24 11:35:55

标签: php xml xpath simplexml

我不知道是否有在xml文件中搜索的方法。例如。我希望使用 AttrList 中的名称 ProductCode 来获取。可能吗 ?这就是我的xml看起来像:

<Product>
    <ProductCode>70-14UF44-00</ProductCode>
    <Vendor>NBM</Vendor>
    <ProductType>Soft. Unsorted application</ProductType>
    <ProductCategory>Software</ProductCategory>
    <ProductDescription>{Bluetooth Driver IVT V.1.4.9.3, 1pk, Full Package, OEM, 1pk for 12M3W/15G3WS, 1pk, 1pk}</ProductDescription>
    <Image>https://www.it4profit.com/catalogimg/wic/1/70-14UF44-00</Image>
    <ProductCard>https://content.it4profit.com/itshop/itemcard_cs.jsp?ITEM=50409104050320315&amp;THEME=asbis&amp;LANG=ro</ProductCard>
    <AttrList>
      <element Name="Tipul licentei" Value="Full Package"/>
      <element Name="License Conditions" Value="OEM"/>
      <element Name="Produs de baza(1)" Value="12M3W/15G3WS"/>
      <element Name="Greutatea bruta a pachetului" Value="1.546 kg"/>
      <element Name="Bucati in pachet" Value="1"/>
    </AttrList>
    <MarketingInfo>
      <element></element>
    </MarketingInfo>
    <Images/>
  </Product>

我正在使用 PHP 中的 SimpleXML 库 尝试使用DOMDocument:

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->Load('produse_catalog.xml');
$xpath = new DOMXPath($doc);
$query = '//ProductCatalog/Product/ProductCode[. = "PMP5297C_QUAD"]';

$entries = $xpath->query($query);
foreach ($entries as $entry) {
    echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
    " by {$entry->previousSibling->nodeValue}\n";
}

结果是:注意:尝试获取非对象的属性。我做错了什么?

2 个答案:

答案 0 :(得分:6)

是的,在这种情况下你可以使用带xpath的simplexml:

$xml = simplexml_load_file('path/to/xml/file.xml');
$name = 'Tipul licentei';
$product_code = '70-14UF44-00';
$products = $xml->xpath("//Product/ProductCode[contains(text(), '$product_code')]/following-sibling::AttrList/element[@Name='$name']");
if(count($products) > 0) { // if found

    $value = (string) $products[0]->attributes()->Value;
    echo $value; // Full Package

}

Sample Output

也可以使用DOMDocument:

$dom = new DOMDocument();
$dom->load('path/to/xml/file.xml');
$xpath = new DOMXpath($dom);

$name = 'Tipul licentei';
$product_code = '70-14UF44-00';
$value = $xpath->evaluate("string(//Product/ProductCode[contains(text(), '$product_code')]/following-sibling::AttrList/element[@Name='$name']/@Value)");
echo $value; // Full Package

答案 1 :(得分:2)

您可以将DOMXPath用于此目的。 取自php.net

的示例
  $doc = new DOMDocument;
  $doc->preserveWhiteSpace = false;
  $doc->Load('book.xml');
  $xpath = new DOMXPath($doc);
  // We starts from the root element
 $query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

 $entries = $xpath->query($query);

 foreach ($entries as $entry) {
   echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
     " by {$entry->previousSibling->nodeValue}\n";
  }