【问题标题】:XML to CSV through PHP - How to grab attribute value?通过 PHP 将 XML 转换为 CSV - 如何获取属性值?
【发布时间】:2020-04-10 10:10:47
【问题描述】:

如何从下面的 XML 中获取 EAN 编号?

<offer>
...
<property EAN="5900017361000"/>
...
</offer>

我的代码没有任何价值。

$ean  = $xpath->query( "//attribute::*[contains(., 'EAN')]" )->item(0)->nodeValue;

整个脚本如下所示:

<?php 

    $xml = file_get_contents("url to remote feed");

    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->standalone=true;
    $dom->strictErrorChecking=false;
    $dom->recover=true;
    $dom->formatOutput=false;

    $dom->loadXML( $xml );
    $errors=serialize( libxml_get_last_error() );
    libxml_clear_errors();

    $cats=$dom->getElementsByTagName('offer');



$xpath = new DOMXPath($dom);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();







    if( !empty( $cats ) && $cats->length > 0 ){
        /* column headers for use in csv */
        $columns = array(
            'Identyfikator',
            'Ilość',
            'Nazwa',
            'VAT',
            'Cena zakupu',
            'Cena zakupu netto',
            'Cena sprzedaży netto',
            'Cena sprzedaży brutto',
            'EAN',
            'Marka',
        );
        /* output file location */
        $file=__DIR__ . '/nowyprodukt.csv';

        /* placeholder array to store results for later writing to csv */
        $data=array();

        foreach( $cats as $cat ){
            ini_set('max_execution_time', 600); //300 seconds = 5 minutes
            set_time_limit(600);

            $item=$cat->childNodes->item(1);
            $identyfikator=trim( $cat->childNodes->item(1)->nodeValue );
            $magazyn  = $cat->getElementsByTagName("onstock")->item(0)->nodeValue;
            $nazwa  = $cat->getElementsByTagName("name")->item(0)->nodeValue;
            $vat  = $cat->getElementsByTagName("vat")->item(0)->nodeValue;
            $cenazakupu  = $cat->getElementsByTagName("price")->item(0)->nodeValue;
            $cenazakupunetto = round($cenazakupu / (100 +$vat) *100, 2);

            $ean  = $xpath->query( "//attribute::*[contains(., 'EAN')]" )->item(0)->nodeValue;


            $marka  = $cat->getElementsByTagName("ext_marka")->item(0)->nodeValue;

            $cenasprzedazynetto = number_format(round($cenazakupunetto, 2) * $margin, 2);

            if (strpos($vat, '8') !== false) {
                $podatek = number_format(round($cenasprzedazynetto, 2) * 1.08, 2);
                $podatek_numer = "2";
            }else{
                $podatek = number_format(round($cenasprzedazynetto, 2) * 1.23, 2);
                $podatek_numer = "1";
            }


            /*
                Generate an array with the values found from querying the XML
            */
            $data[]=array(
                $columns[0] =>  $identyfikator,
                $columns[1] =>  $magazyn,
                $columns[2] =>  $nazwa,
                $columns[3] =>  $podatek_numer,
                $columns[4] =>  $cenazakupu,
                $columns[5] =>  $cenazakupunetto,
                $columns[6] =>  $cenasprzedazynetto,
                $columns[7] =>  $podatek,
                $columns[8] =>  $ean,
                $columns[9] =>  $marka,

                );
        }
        /*
            Write the headers and csv data to file
        */
        if( !empty( $data ) ){
            $f = fopen( $file, 'w' );
            fputcsv( $f, $columns );
            foreach($data as $arr)fputcsv($f,$arr);
            fclose($f);

            echo count( $data ) . ' wierszy zapisanych w ' . $file;
        }
    }
    $dom=null;  


?>

一切都很好,除了 EAN,因为它的结构很奇怪。

你能帮帮我吗?

【问题讨论】:

  • ...-&gt;item(0)-&gt;nodeValue应该是-&gt;getAttribute('ean'),nodeValue是节点本身的值。
  • 未捕获的错误:调用未定义的方法 DOMNodeList::getAttribute()
  • 仍然需要-&gt;item(0),因为错误表明您在列表上而不是节点上调用getAttruibute
  • $ean = $xpath->query("//attribute::*[contains(., 'EAN')]" )->item(0)->getAttribute('ean') ;现在我有另一个错误 Uncaught Error: Call to a member function getAttribute() on null in
  • 错误似乎在你的 XPath 中,在下面添加答案。

标签: php xml csv


【解决方案1】:

这是一个如何获取“EAN”属性值的工作示例。

$xml = <<<HERE
<offer>
<property EAN="5900017361000"/>
<property EAN="6865321215121"/>
<property EAN="5464321585637"/>
</offer>
HERE;

$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
$result = $xpath->query("//@EAN");

for ($i = 0; $i < $result->length; $i++)
{
    echo $result->item($i)->nodeValue;
}

【讨论】:

  • 感谢您帮助我。您的代码运行良好,但现在我不知道如何在我的脚本中实现它。关键是将 EAN 编号放在第八列。
  • 您需要为 XPath 查询的上下文传递当前的 offer 节点,$ean = $xpath-&gt;query("//@EAN", $cat) 应该可以作为替代品。
  • 还是想不通,怎么办?能否请您分享我的代码以及您已经实施的修改?
  • 我通过添加 $ean = $cat->getElementsByTagName('property')->item(0)->getAttribute('EAN'); 解决了它
猜你喜欢
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 1970-01-01
相关资源
最近更新 更多