查找并替换html(Zend_Dom_Query + createElement()):在非对象上调用成员函数createElement()

时间:2015-05-19 06:51:37

标签: php magento dom zend-dom-query

我需要找到并替换html代码中的一些html元素(我按照这个答案:Getting an element from PHP DOM and changing its value),这样做我用以下内容检索内容:

$transport = $observer->getTransport();
$html = $transport->getHtml();
$dom = new Zend_Dom_Query($html);
$document = $dom->getDocument();

这就是结果:

<div class="page-title category-title">
     <h1>Title</h1>
</div>
<div class="category-products">
    <div class="toolbar">
        <div class="pager">
            <p class="amount">Items 2 to 2 of 2 total</p>
            <div class="limiter">
                <label>Show</label>
                <select onchange="setLocation(this.value)">
                    <option value="limit=1" selected="selected">1</option>
                </select>per page</div>
            <div class="pages"> <strong>Page:</strong>
                <ol>
                    <li> 
                        <a class="previous i-previous" href="p=1" title="Previous">
                            <img src="skin/frontend/default/default/images/pager_arrow_left.gif" alt="Previous" class="v-middle" />
                        </a>
                    </li>
                    <li><a href="p=1">1</a>
                    </li>
                    <li class="current">2</li>
                </ol>
            </div>
        </div>
        <div class="sorter">
            <p class="view-mode">
                <label>View as:</label> <strong title="Grid" class="grid">Grid</strong>&nbsp; <a href="mode=list" title="List" class="list">List</a>&nbsp;</p>
            <div class="sort-by">
                <label>Sort By</label>
                <select onchange="setLocation(this.value)">
                    <option value="dir=asc&amp;order=position" selected="selected">Position</option>
                    <option value="dir=asc&amp;order=name">Name</option>
                    <option value="dir=asc&amp;order=price">Price</option>
                </select> <a href="dir=desc&amp;order=position" title="Set Descending Direction"><img src="skin/frontend/default/default/images/i_asc_arrow.gif" alt="Set Descending Direction" class="v-middle" /></a>

            </div>
        </div>
    </div>
    <ul class="products-grid">
        <li class="item first"> 
            <a href="test/a-2.html" title="a" class="product-image">
                <img src="media/catalog/product/cache/1/small_image/135x/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/small_image.jpg" width="135" height="135" alt="a" />
            </a>
            <h2 class="product-name"><a href="test/a-2.html" title="a">a</a></h2>
            <div class="price-box"> <span class="regular-price" id="product-price-2">
                <span class="price">$1.00</span> </span>
            </div>
            <div class="actions">
                <button type="button" title="Add to Cart" class="button btn-cart" onclick="setLocation('test/a-2.html')"><span><span>Add to Cart</span></span>
                </button>
                <ul class="add-to-links">
                    <li>
                        <a href="wishlist/index/add/product/2/form_key/Ptxz8SA6DEWOGLF7/" class="link-wishlist">Add to Wishlist</a>
                    </li>
                    <li>
                        <span class="separator">|</span>  <a href="catalog/product_compare/add/product/2/uenc/aHR0cDovL2Zhcm1hY2lhY2Fsb2luaS5jb20vbWluaWNvbXBhcmVkZW1vL2luZGV4LnBocC90ZXN0Lmh0bWw_cD0y/form_key/Ptxz8SA6DEWOGLF7/" class="link-compare">Add to Compare</a>
                    </li>
                </ul>
            </div>
        </li>
    </ul>
    <script type="text/javascript">
        decorateGeneric($$('ul.products-grid'), ['odd', 'even', 'first', 'last'])
    </script>
    <div class="toolbar-bottom">
        <div class="toolbar">
            <div class="pager">
                <p class="amount">Items 2 to 2 of 2 total</p>
                <div class="limiter">
                    <label>Show</label>
                    <select onchange="setLocation(this.value)">
                        <option value="limit=1" selected="selected">1</option>
                    </select>per page</div>
                <div class="pages"> <strong>Page:</strong>
                    <ol>
                        <li> 
                        <a class="previous i-previous" href="p=1" title="Previous">
                            <img src="skin/frontend/default/default/images/pager_arrow_left.gif" alt="Previous" class="v-middle" />
                        </a>
                        </li>
                        <li><a href="p=1">1</a>
                        </li>
                        <li class="current">2</li>
                    </ol>
                </div>
            </div>
            <div class="sorter">
                <p class="view-mode">
                    <label>View as:</label> <strong title="Grid" class="grid">Grid</strong>&nbsp; <a href="mode=list" title="List" class="list">List</a>&nbsp;</p>
                <div class="sort-by">
                    <label>Sort By</label>
                    <select onchange="setLocation(this.value)">
                        <option value="dir=asc&amp;order=position" selected="selected">Position</option>
                        <option value="dir=asc&amp;order=name">Name</option>
                        <option value="dir=asc&amp;order=price">Price</option>
                    </select> <a href="dir=desc&amp;order=position" title="Set Descending Direction"><img src="skin/frontend/default/default/images/i_asc_arrow.gif" alt="Set Descending Direction" class="v-middle" /></a>
                </div>
            </div>
        </div>
    </div>
</div>

要查找我使用的Zend_Dom_Query

$transport = $observer->getTransport();
$html = $transport->getHtml();
$dom = new Zend_Dom_Query($html);
$document = $dom->getDocument();

if(!is_object($document)){
    Mage::log(print_r($document, TRUE), null, 'mylogfile1.log');
    $transport->setHtml($html);
    exit();
}

$node = $document->createElement("p", "This product isn't available in your country.");

不幸的是它总是在obeject检查中退出,否则它会返回此错误:

Fatal error: Call to a member function createElement() on a non-object

修改 完整的代码,如果有人想看到我检索内容的位置(我已经添加了一些注释以便更清楚):

//retrieve html from observer
$transport = $observer->getTransport();
$html = $transport->getHtml();

//Retrieve other info
$stored = json_decode(Mage::getStoreConfig('razorphyn/country/buttons'));
$theme=trim(Mage::getSingleton('core/design_package')->getTheme('frontend'));
$dom = new Zend_Dom_Query($html);
$document = $dom->getDocument();

//check if $document is an object
if(!is_object($document)){
    Mage::log(print_r($document, TRUE), null, 'mylogfile1.log');


$transport->setHtml($html);
    exit();
}

//Create node that will replace the finded ones
$node = $document->createElement("p", "This product isn't available in your country.");

$elArray=array();
$productsIds= array();

//Retrieve products id if button and store query results
if($stored[$theme]['isOnClick']){
    $queryDom='button'.$stored[$theme]['class'].'[onclick*="/checkout/cart/add/"]';
    $results = $dom->query($queryDom);
    foreach ($results as $result) {
        preg_match("/checkout\/cart\/add.+\/([0-9]+)\//",$result->getAttribute('onclick'),$currentProdId);
        $elArray[$currentProdId[0]]=$result;
        $productsIds[]=$currentProdId[0];
    }
}
//Retrieve products id if form, runa nother query to find button and store query results
else{
    $queryDom='form'.$stored[$theme]['formId'].'[action*="/checkout/cart/add/"]';
    $results = $dom->query($queryDom);
    foreach ($results as $result) {
        preg_match("/checkout\/cart\/add.+\/([0-9]+)\//",$result->getAttribute('action'),$currentProdId);
        if($currentProdId[0] && is_numeric($currentProdId[0])){
            $productsIds[]=$currentProdId[0];

            $formDOM = new Zend_Dom_Query($result);
            $formButton = $dom->query('button'.$stored[$theme]['class']);

            foreach($formButton as $child){
                $elArray[$currentProdId[0]]=$child;
            }
        }
    }
}

//Retrieve info from table
$collection = Mage::getModel('razorphyn_country/product')->getCollection()
                                                         ->addFieldToFilter('active', 1)
                                                         ->addAttributeToFilter('productId', array('in' => $productsIds));

$res = $collection->getFirstItem();
$country = Mage::getSingleton('core/session')->getCustomerCountry;

//Replace items
if(isset($res->allowed)){
    foreach($collection as $res){
        if(isset($res->allowed) && (($res->allowed==0 && strpos($res->country, $country) !== false) || ($res->allowed==1 && strpos($res->country, $country) === false))){
            $document = $document->replaceChild($node,$elArray[$res->productId]);
        }
    }
}

//Return edited html
$html = $document->saveHTML();
$transport->setHtml($html);

1 个答案:

答案 0 :(得分:0)

您是否意识到您没有选择元素,而是使用createElement()创建元素?

我不确定你想放置段落的位置,但是在div.category-products中说。所以让我们试试这样的事情;

$transport = $observer->getTransport();
$html = $transport->getHtml();
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath  = new DOMXPath($dom);
$nodes  = $xpath->query('//div[@class="category-products"]');
foreach($nodes as $node) {
    $newNode = $dom->createElement("p", "This product isn't available in your country.");
    $node->insertBefore($newNode, $node->nextSibling());
}