php - 查找并替换 html(Zend_Dom_Query+createElement()) : Call to a member function createElement() on a non-object

标签 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.");

不幸的是它总是在对象检查中退出,否则它会返回这个错误:

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);

最佳答案

你意识到你不是在选择一个元素,而是用 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());
}

关于php - 查找并替换 html(Zend_Dom_Query+createElement()) : Call to a member function createElement() on a non-object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30318611/

相关文章:

Magento - 无法应用目录价格规则

Magento - 使用升级脚本向表列添加索引

Magento - 非卖品

php - DOM/xpath 与 php 一起使用来处理外部站点?

javascript - document.getElementById 找不到 qUnit DOM 元素

php - 使用 PHP 获取 IP 信息

php - 在 php echo 语句中使用参数调用 javascript 函数

php - 警告 : ssh2_connect(): Failed overriding server to client COMP method

javascript - 从 DOM 中隐藏数据(保护数据)

php - 为什么我会从 CURL 随机收到 "Unknown SSL protocol error"?